1.0.6.38: thread and interrupt safe ADD/REMOVE-METHOD
[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       (setf (slot-value class 'slots) (compute-slots class))))
538   ;; Comment from Gerd's PCL, 2003-05-15:
539   ;;
540   ;; We don't ADD-SLOT-ACCESSORS here because we don't want to
541   ;; override condition accessors with generic functions.  We do this
542   ;; differently.
543   ;;
544   ;; ??? What does the above comment mean and why is it a good idea?
545   ;; CMUCL (which still as of 2005-11-18 uses this code and has this
546   ;; comment) loses slot information in its condition classes:
547   ;; DIRECT-SLOTS is always NIL.  We have the right information, so we
548   ;; remove slot accessors but never put them back.  I've added a
549   ;; REINITIALIZE-INSTANCE :AFTER (CONDITION-CLASS) method, but what
550   ;; was meant to happen?  -- CSR, 2005-11-18
551   (update-pv-table-cache-info class))
552
553 (defmethod direct-slot-definition-class ((class condition-class)
554                                          &rest initargs)
555   (declare (ignore initargs))
556   (find-class 'condition-direct-slot-definition))
557
558 (defmethod effective-slot-definition-class ((class condition-class)
559                                             &rest initargs)
560   (declare (ignore initargs))
561   (find-class 'condition-effective-slot-definition))
562
563 (defmethod finalize-inheritance ((class condition-class))
564   (aver (slot-value class 'finalized-p))
565   nil)
566
567 (defmethod compute-effective-slot-definition
568     ((class condition-class) slot-name dslotds)
569   (let ((slotd (call-next-method)))
570     (setf (slot-definition-reader-function slotd)
571           (lambda (x)
572             (handler-case (condition-reader-function x slot-name)
573               ;; FIXME: FIND-SLOT-DEFAULT throws an error if the slot
574               ;; is unbound; maybe it should be a CELL-ERROR of some
575               ;; sort?
576               (error () (values (slot-unbound class x slot-name))))))
577     (setf (slot-definition-writer-function slotd)
578           (lambda (v x)
579             (condition-writer-function x v slot-name)))
580     (setf (slot-definition-boundp-function slotd)
581           (lambda (x)
582             (multiple-value-bind (v c)
583                 (ignore-errors (condition-reader-function x slot-name))
584               (declare (ignore v))
585               (null c))))
586     slotd))
587
588 (defmethod compute-slots ((class condition-class))
589   (mapcan (lambda (superclass)
590             (mapcar (lambda (dslotd)
591                       (compute-effective-slot-definition
592                        class (slot-definition-name dslotd) (list dslotd)))
593                     (class-direct-slots superclass)))
594           (reverse (slot-value class '%class-precedence-list))))
595
596 (defmethod compute-slots :around ((class condition-class))
597   (let ((eslotds (call-next-method)))
598     (mapc #'initialize-internal-slot-functions eslotds)
599     eslotds))
600
601 (defmethod shared-initialize :after
602     ((slotd structure-slot-definition) slot-names &key
603      (allocation :instance) allocation-class)
604   (declare (ignore slot-names allocation-class))
605   (unless (eq allocation :instance)
606     (error "Structure slots must have :INSTANCE allocation.")))
607
608 (defun make-structure-class-defstruct-form (name direct-slots include)
609   (let* ((conc-name (format-symbol *package* "~S structure class " name))
610          (constructor (format-symbol *package* "~Aconstructor" conc-name))
611          (defstruct `(defstruct (,name
612                                  ,@(when include
613                                          `((:include ,(class-name include))))
614                                  (:predicate nil)
615                                  (:conc-name ,conc-name)
616                                  (:constructor ,constructor ())
617                                  (:copier nil))
618                       ,@(mapcar (lambda (slot)
619                                   `(,(slot-definition-name slot)
620                                     +slot-unbound+))
621                                 direct-slots)))
622          (reader-names (mapcar (lambda (slotd)
623                                  (list 'slot-accessor name
624                                        (slot-definition-name slotd)
625                                        'reader))
626                                direct-slots))
627          (writer-names (mapcar (lambda (slotd)
628                                  (list 'slot-accessor name
629                                        (slot-definition-name slotd)
630                                        'writer))
631                                direct-slots))
632          (readers-init
633            (mapcar (lambda (slotd reader-name)
634                      (let ((accessor
635                              (slot-definition-defstruct-accessor-symbol
636                               slotd)))
637                        `(defun ,reader-name (obj)
638                          (declare (type ,name obj))
639                          (,accessor obj))))
640                    direct-slots reader-names))
641          (writers-init
642            (mapcar (lambda (slotd writer-name)
643                      (let ((accessor
644                              (slot-definition-defstruct-accessor-symbol
645                               slotd)))
646                        `(defun ,writer-name (nv obj)
647                          (declare (type ,name obj))
648                          (setf (,accessor obj) nv))))
649                    direct-slots writer-names))
650          (defstruct-form
651              `(progn
652                ,defstruct
653                ,@readers-init ,@writers-init
654                (cons nil nil))))
655     (values defstruct-form constructor reader-names writer-names)))
656
657 (defun make-defstruct-allocation-function (class)
658   ;; FIXME: Why don't we go class->layout->info == dd
659   (let ((dd (find-defstruct-description (class-name class))))
660     (lambda ()
661       (sb-kernel::%make-instance-with-layout
662        (sb-kernel::compiler-layout-or-lose (dd-name dd))))))
663
664 (defmethod shared-initialize :after
665     ((class structure-class) slot-names &key
666      (direct-superclasses nil direct-superclasses-p)
667      (direct-slots nil direct-slots-p)
668      direct-default-initargs)
669   (declare (ignore slot-names direct-default-initargs))
670   (if direct-superclasses-p
671       (setf (slot-value class 'direct-superclasses)
672             (or direct-superclasses
673                 (setq direct-superclasses
674                       (and (not (eq (class-name class) 'structure-object))
675                            (list *the-class-structure-object*)))))
676       (setq direct-superclasses (slot-value class 'direct-superclasses)))
677   (let* ((name (class-name class))
678          (from-defclass-p (slot-value class 'from-defclass-p))
679          (defstruct-p (or from-defclass-p (not (structure-type-p name)))))
680     (if direct-slots-p
681         (setf (slot-value class 'direct-slots)
682               (setq direct-slots
683                     (mapcar (lambda (pl)
684                               (when defstruct-p
685                                 (let* ((slot-name (getf pl :name))
686                                        (accessor
687                                         (format-symbol *package*
688                                                        "~S structure class ~A"
689                                                        name slot-name)))
690                                   (setq pl (list* :defstruct-accessor-symbol
691                                                   accessor pl))))
692                               (make-direct-slotd class pl))
693                             direct-slots)))
694         (setq direct-slots (slot-value class 'direct-slots)))
695     (if defstruct-p
696         (let ((include (car (slot-value class 'direct-superclasses))))
697           (multiple-value-bind (defstruct-form constructor reader-names writer-names)
698               (make-structure-class-defstruct-form name direct-slots include)
699             (unless (structure-type-p name) (eval defstruct-form))
700             (mapc (lambda (dslotd reader-name writer-name)
701                     (let* ((reader (gdefinition reader-name))
702                            (writer (when (fboundp writer-name)
703                                      (gdefinition writer-name))))
704                       (setf (slot-value dslotd 'internal-reader-function)
705                             reader)
706                       (setf (slot-value dslotd 'internal-writer-function)
707                             writer)))
708                   direct-slots reader-names writer-names)
709             (setf (slot-value class 'defstruct-form) defstruct-form)
710             (setf (slot-value class 'defstruct-constructor) constructor)))
711         (setf (slot-value class 'defstruct-constructor)
712               (make-defstruct-allocation-function class)))
713     (add-direct-subclasses class direct-superclasses)
714     (setf (slot-value class '%class-precedence-list)
715           (compute-class-precedence-list class))
716     (setf (slot-value class 'cpl-available-p) t)
717     (setf (slot-value class 'slots) (compute-slots class))
718     (let ((lclass (find-classoid (class-name class))))
719       (setf (classoid-pcl-class lclass) class)
720       (setf (slot-value class 'wrapper) (classoid-layout lclass)))
721     (setf (slot-value class 'finalized-p) t)
722     (update-pv-table-cache-info class)
723     (add-slot-accessors class direct-slots)))
724
725 (defmethod direct-slot-definition-class ((class structure-class) &rest initargs)
726   (declare (ignore initargs))
727   (find-class 'structure-direct-slot-definition))
728
729 (defmethod finalize-inheritance ((class structure-class))
730   nil) ; always finalized
731 \f
732 (defun add-slot-accessors (class dslotds)
733   (fix-slot-accessors class dslotds 'add))
734
735 (defun remove-slot-accessors (class dslotds)
736   (fix-slot-accessors class dslotds 'remove))
737
738 (defun fix-slot-accessors (class dslotds add/remove)
739   (flet ((fix (gfspec name r/w doc)
740            (let ((gf (cond ((eq add/remove 'add)
741                             (or (find-generic-function gfspec nil)
742                                 (ensure-generic-function
743                                  gfspec :lambda-list (case r/w
744                                                        (r '(object))
745                                                        (w '(new-value object))))))
746                            (t
747                             (find-generic-function gfspec nil)))))
748              (when gf
749                (case r/w
750                  (r (if (eq add/remove 'add)
751                         (add-reader-method class gf name doc)
752                         (remove-reader-method class gf)))
753                  (w (if (eq add/remove 'add)
754                         (add-writer-method class gf name doc)
755                         (remove-writer-method class gf))))))))
756     (dolist (dslotd dslotds)
757       (let ((slot-name (slot-definition-name dslotd))
758             (slot-doc (%slot-definition-documentation dslotd)))
759         (dolist (r (slot-definition-readers dslotd))
760           (fix r slot-name 'r slot-doc))
761         (dolist (w (slot-definition-writers dslotd))
762           (fix w slot-name 'w slot-doc))))))
763 \f
764 (defun add-direct-subclasses (class supers)
765   (dolist (super supers)
766     (unless (memq class (class-direct-subclasses class))
767       (add-direct-subclass super class))))
768
769 (defmethod finalize-inheritance ((class std-class))
770   (update-class class t))
771
772 (defmethod finalize-inheritance ((class forward-referenced-class))
773   ;; FIXME: should we not be thinking a bit about what kinds of error
774   ;; we're throwing?  Maybe we need a clos-error type to mix in?  Or
775   ;; possibly a forward-referenced-class-error, though that's
776   ;; difficult given e.g. class precedence list calculations...
777   (error
778    "~@<FINALIZE-INHERITANCE was called on a forward referenced class:~
779        ~2I~_~S~:>"
780    class))
781
782 \f
783 (defun class-has-a-forward-referenced-superclass-p (class)
784   (or (forward-referenced-class-p class)
785       (some #'class-has-a-forward-referenced-superclass-p
786             (class-direct-superclasses class))))
787
788 ;;; This is called by :after shared-initialize whenever a class is initialized
789 ;;; or reinitialized. The class may or may not be finalized.
790 (defun update-class (class finalizep)
791   (without-package-locks
792     (when (or finalizep (class-finalized-p class))
793       (update-cpl class (compute-class-precedence-list class))
794       ;; This invocation of UPDATE-SLOTS, in practice, finalizes the
795       ;; class.
796       (update-slots class (compute-slots class))
797       (update-gfs-of-class class)
798       (update-initargs class (compute-default-initargs class))
799       (update-ctors 'finalize-inheritance :class class))
800     (dolist (sub (class-direct-subclasses class))
801       (update-class sub nil))))
802
803 (define-condition cpl-protocol-violation (reference-condition error)
804   ((class :initarg :class :reader cpl-protocol-violation-class)
805    (cpl :initarg :cpl :reader cpl-protocol-violation-cpl))
806   (:default-initargs :references (list '(:sbcl :node "Metaobject Protocol")))
807   (:report
808    (lambda (c s)
809      (format s "~@<Protocol violation: the ~S class ~S ~
810                 ~:[has~;does not have~] the class ~S in its ~
811                 class precedence list: ~S.~@:>"
812              (class-name (class-of (cpl-protocol-violation-class c)))
813              (cpl-protocol-violation-class c)
814              (eq (class-of (cpl-protocol-violation-class c))
815                  *the-class-funcallable-standard-class*)
816              (find-class 'function)
817              (cpl-protocol-violation-cpl c)))))
818
819 (defun update-cpl (class cpl)
820   (when (eq (class-of class) *the-class-standard-class*)
821     (when (find (find-class 'function) cpl)
822       (error 'cpl-protocol-violation :class class :cpl cpl)))
823   (when (eq (class-of class) *the-class-funcallable-standard-class*)
824     (unless (find (find-class 'function) cpl)
825       (error 'cpl-protocol-violation :class class :cpl cpl)))
826   (if (class-finalized-p class)
827       (unless (and (equal (class-precedence-list class) cpl)
828                    (dolist (c cpl t)
829                      (when (position :class (class-direct-slots c)
830                                      :key #'slot-definition-allocation)
831                        (return nil))))
832         ;; comment from the old CMU CL sources:
833         ;;   Need to have the cpl setup before update-lisp-class-layout
834         ;;   is called on CMU CL.
835         (setf (slot-value class '%class-precedence-list) cpl)
836         (setf (slot-value class 'cpl-available-p) t)
837         (force-cache-flushes class))
838       (progn
839         (setf (slot-value class '%class-precedence-list) cpl)
840         (setf (slot-value class 'cpl-available-p) t)))
841   (update-class-can-precede-p cpl))
842
843 (defun update-class-can-precede-p (cpl)
844   (when cpl
845     (let ((first (car cpl)))
846       (dolist (c (cdr cpl))
847         (pushnew c (slot-value first 'can-precede-list))))
848     (update-class-can-precede-p (cdr cpl))))
849
850 (defun class-can-precede-p (class1 class2)
851   (member class2 (class-can-precede-list class1)))
852
853 (defun update-slots (class eslotds)
854   (let ((instance-slots ())
855         (class-slots    ()))
856     (dolist (eslotd eslotds)
857       (let ((alloc (slot-definition-allocation eslotd)))
858         (case alloc
859           (:instance (push eslotd instance-slots))
860           (:class (push eslotd class-slots)))))
861
862     ;; If there is a change in the shape of the instances then the
863     ;; old class is now obsolete.
864     (let* ((nlayout (mapcar #'slot-definition-name
865                             (sort instance-slots #'<
866                                   :key #'slot-definition-location)))
867            (nslots (length nlayout))
868            (nwrapper-class-slots (compute-class-slots class-slots))
869            (owrapper (when (class-finalized-p class)
870                        (class-wrapper class)))
871            (olayout (when owrapper
872                       (wrapper-instance-slots-layout owrapper)))
873            (owrapper-class-slots (and owrapper (wrapper-class-slots owrapper)))
874            (nwrapper
875             (cond ((null owrapper)
876                    (make-wrapper nslots class))
877                   ((and (equal nlayout olayout)
878                         (not
879                          (loop for o in owrapper-class-slots
880                                for n in nwrapper-class-slots
881                                do (unless (eq (car o) (car n)) (return t)))))
882                    owrapper)
883                   (t
884                    ;; This will initialize the new wrapper to have the
885                    ;; same state as the old wrapper. We will then have
886                    ;; to change that. This may seem like wasted work
887                    ;; (and it is), but the spec requires that we call
888                    ;; MAKE-INSTANCES-OBSOLETE.
889                    (make-instances-obsolete class)
890                    (class-wrapper class)))))
891
892       (with-slots (wrapper slots) class
893         (update-lisp-class-layout class nwrapper)
894         (setf slots eslotds
895               (wrapper-instance-slots-layout nwrapper) nlayout
896               (wrapper-class-slots nwrapper) nwrapper-class-slots
897               (layout-length nwrapper) nslots
898               wrapper nwrapper)
899         (do* ((slots (slot-value class 'slots) (cdr slots))
900               (dupes nil))
901              ((null slots)
902               (when dupes
903                 (style-warn
904                  "~@<slot names with the same SYMBOL-NAME but ~
905                   different SYMBOL-PACKAGE (possible package problem) ~
906                   for class ~S:~4I~@:_~<~@{~S~^~:@_~}~:>~@:>"
907                   class dupes)))
908           (let* ((slot (car slots))
909                  (oslots (remove (slot-definition-name slot) (cdr slots)
910                                  :test #'string/=
911                                  :key #'slot-definition-name)))
912             (when oslots
913               (pushnew (cons (slot-definition-name slot)
914                              (mapcar #'slot-definition-name oslots))
915                        dupes
916                        :test #'string= :key #'car)))))
917       (setf (slot-value class 'finalized-p) t)
918       (unless (eq owrapper nwrapper)
919         (update-pv-table-cache-info class)
920         (maybe-update-standard-class-locations class)))))
921
922 (defun compute-class-slots (eslotds)
923   (let (collect)
924     (dolist (eslotd eslotds (nreverse collect))
925       (let ((cell (assoc (slot-definition-name eslotd)
926                          (class-slot-cells
927                           (slot-definition-allocation-class eslotd)))))
928         (aver cell)
929         (push cell collect)))))
930
931 (defun update-gfs-of-class (class)
932   (when (and (class-finalized-p class)
933              (let ((cpl (class-precedence-list class)))
934                (or (member *the-class-slot-class* cpl)
935                    (member *the-class-standard-effective-slot-definition*
936                            cpl))))
937     (let ((gf-table (make-hash-table :test 'eq)))
938       (labels ((collect-gfs (class)
939                  (dolist (gf (specializer-direct-generic-functions class))
940                    (setf (gethash gf gf-table) t))
941                  (mapc #'collect-gfs (class-direct-superclasses class))))
942         (collect-gfs class)
943         (maphash (lambda (gf ignore)
944                    (declare (ignore ignore))
945                    (update-gf-dfun class gf))
946                  gf-table)))))
947
948 (defun update-initargs (class inits)
949   (setf (plist-value class 'default-initargs) inits))
950 \f
951 (defmethod compute-default-initargs ((class slot-class))
952   (let ((initargs (loop for c in (class-precedence-list class)
953                         append (class-direct-default-initargs c))))
954     (delete-duplicates initargs :test #'eq :key #'car :from-end t)))
955 \f
956 ;;;; protocols for constructing direct and effective slot definitions
957
958 (defmethod direct-slot-definition-class ((class std-class) &rest initargs)
959   (declare (ignore initargs))
960   (find-class 'standard-direct-slot-definition))
961
962 (defun make-direct-slotd (class initargs)
963   (apply #'make-instance
964          (apply #'direct-slot-definition-class class initargs)
965          :class class
966          initargs))
967
968 ;;; I (CSR) am not sure, but I believe that the particular order of
969 ;;; slots is quite important: it is ideal to attempt to have a
970 ;;; constant slot location for the same notional slots as much as
971 ;;; possible, so that clever discriminating functions (ONE-INDEX et
972 ;;; al.) have a chance of working.  The below at least walks through
973 ;;; the slots predictably, but maybe it would be good to compute some
974 ;;; kind of optimal slot layout by looking at locations of slots in
975 ;;; superclasses?
976 (defun std-compute-slots (class)
977   ;; As specified, we must call COMPUTE-EFFECTIVE-SLOT-DEFINITION once
978   ;; for each different slot name we find in our superclasses. Each
979   ;; call receives the class and a list of the dslotds with that name.
980   ;; The list is in most-specific-first order.
981   (let ((name-dslotds-alist ()))
982     (dolist (c (reverse (class-precedence-list class)))
983       (dolist (slot (class-direct-slots c))
984         (let* ((name (slot-definition-name slot))
985                (entry (assq name name-dslotds-alist)))
986           (if entry
987               (push slot (cdr entry))
988               (push (list name slot) name-dslotds-alist)))))
989     (mapcar (lambda (direct)
990               (compute-effective-slot-definition class
991                                                  (car direct)
992                                                  (cdr direct)))
993             (nreverse name-dslotds-alist))))
994
995 (defmethod compute-slots ((class standard-class))
996   (std-compute-slots class))
997 (defmethod compute-slots ((class funcallable-standard-class))
998   (std-compute-slots class))
999
1000 (defun std-compute-slots-around (class eslotds)
1001   (let ((location -1))
1002     (dolist (eslotd eslotds eslotds)
1003       (setf (slot-definition-location eslotd)
1004             (case (slot-definition-allocation eslotd)
1005               (:instance
1006                (incf location))
1007               (:class
1008                (let* ((name (slot-definition-name eslotd))
1009                       (from-class
1010                        (or
1011                         (slot-definition-allocation-class eslotd)
1012                         ;; we get here if the user adds an extra slot
1013                         ;; himself...
1014                         (setf (slot-definition-allocation-class eslotd)
1015                               class)))
1016                       ;; which raises the question of what we should
1017                       ;; do if we find that said user has added a slot
1018                       ;; with the same name as another slot...
1019                       (cell (or (assq name (class-slot-cells from-class))
1020                                 (let ((c (cons name +slot-unbound+)))
1021                                   (push c (class-slot-cells from-class))
1022                                   c))))
1023                  (aver (consp cell))
1024                  (if (eq +slot-unbound+ (cdr cell))
1025                      ;; We may have inherited an initfunction
1026                      (let ((initfun (slot-definition-initfunction eslotd)))
1027                        (if initfun
1028                            (rplacd cell (funcall initfun))
1029                            cell))
1030                      cell)))))
1031       (unless (slot-definition-class eslotd)
1032         (setf (slot-definition-class eslotd) class))
1033       (initialize-internal-slot-functions eslotd))))
1034
1035 (defmethod compute-slots :around ((class standard-class))
1036   (let ((eslotds (call-next-method)))
1037     (std-compute-slots-around class eslotds)))
1038 (defmethod compute-slots :around ((class funcallable-standard-class))
1039   (let ((eslotds (call-next-method)))
1040     (std-compute-slots-around class eslotds)))
1041
1042 (defmethod compute-slots ((class structure-class))
1043   (mapcan (lambda (superclass)
1044             (mapcar (lambda (dslotd)
1045                       (compute-effective-slot-definition
1046                        class
1047                        (slot-definition-name dslotd)
1048                        (list dslotd)))
1049                     (class-direct-slots superclass)))
1050           (reverse (slot-value class '%class-precedence-list))))
1051
1052 (defmethod compute-slots :around ((class structure-class))
1053   (let ((eslotds (call-next-method)))
1054     (mapc #'initialize-internal-slot-functions eslotds)
1055     eslotds))
1056
1057 (defmethod compute-effective-slot-definition ((class slot-class) name dslotds)
1058   (declare (ignore name))
1059   (let* ((initargs (compute-effective-slot-definition-initargs class dslotds))
1060          (class (apply #'effective-slot-definition-class class initargs)))
1061     (apply #'make-instance class initargs)))
1062
1063 (defmethod effective-slot-definition-class ((class std-class) &rest initargs)
1064   (declare (ignore initargs))
1065   (find-class 'standard-effective-slot-definition))
1066
1067 (defmethod effective-slot-definition-class ((class structure-class) &rest initargs)
1068   (declare (ignore initargs))
1069   (find-class 'structure-effective-slot-definition))
1070
1071 (defmethod compute-effective-slot-definition-initargs
1072     ((class slot-class) direct-slotds)
1073   (let* ((name nil)
1074          (initfunction nil)
1075          (initform nil)
1076          (initargs nil)
1077          (allocation nil)
1078          (allocation-class nil)
1079          (type t)
1080          (type-check-function nil)
1081          (documentation nil)
1082          (documentationp nil)
1083          (namep  nil)
1084          (initp  nil)
1085          (allocp nil))
1086
1087     (dolist (slotd direct-slotds)
1088       (when slotd
1089         (unless namep
1090           (setq name (slot-definition-name slotd)
1091                 namep t))
1092         (unless initp
1093           (when (slot-definition-initfunction slotd)
1094             (setq initform (slot-definition-initform slotd)
1095                   initfunction (slot-definition-initfunction slotd)
1096                   initp t)))
1097         (unless documentationp
1098           (when (%slot-definition-documentation slotd)
1099             (setq documentation (%slot-definition-documentation slotd)
1100                   documentationp t)))
1101         (unless allocp
1102           (setq allocation (slot-definition-allocation slotd)
1103                 allocation-class (slot-definition-class slotd)
1104                 allocp t))
1105         (setq initargs (append (slot-definition-initargs slotd) initargs))
1106         (let ((fun (slot-definition-type-check-function slotd)))
1107           (when fun
1108             (setf type-check-function
1109                   (if type-check-function
1110                       (let ((old-function type-check-function))
1111                         (lambda (value)
1112                           (funcall old-function value)
1113                           (funcall fun value)))
1114                       fun))))
1115         (let ((slotd-type (slot-definition-type slotd)))
1116           (setq type (cond
1117                        ((eq type t) slotd-type)
1118                        ;; This pairwise type intersection is perhaps a
1119                        ;; little inefficient and inelegant, but it's
1120                        ;; unlikely to lie on the critical path.  Shout
1121                        ;; if I'm wrong.  -- CSR, 2005-11-24
1122                        (t (type-specifier
1123                            (specifier-type `(and ,type ,slotd-type)))))))))
1124     (list :name name
1125           :initform initform
1126           :initfunction initfunction
1127           :initargs initargs
1128           :allocation allocation
1129           :allocation-class allocation-class
1130           :type type
1131           'type-check-function type-check-function
1132           :class class
1133           :documentation documentation)))
1134
1135 (defmethod compute-effective-slot-definition-initargs :around
1136     ((class structure-class) direct-slotds)
1137   (let ((slotd (car direct-slotds)))
1138     (list* :defstruct-accessor-symbol
1139            (slot-definition-defstruct-accessor-symbol slotd)
1140            :internal-reader-function
1141            (slot-definition-internal-reader-function slotd)
1142            :internal-writer-function
1143            (slot-definition-internal-writer-function slotd)
1144            (call-next-method))))
1145 \f
1146 ;;; NOTE: For bootstrapping considerations, these can't use MAKE-INSTANCE
1147 ;;;       to make the method object. They have to use make-a-method which
1148 ;;;       is a specially bootstrapped mechanism for making standard methods.
1149 (defmethod reader-method-class ((class slot-class) direct-slot &rest initargs)
1150   (declare (ignore direct-slot initargs))
1151   (find-class 'standard-reader-method))
1152
1153 (defmethod add-reader-method ((class slot-class) generic-function slot-name slot-documentation)
1154   (add-method generic-function
1155               (make-a-method 'standard-reader-method
1156                              ()
1157                              (list (or (class-name class) 'object))
1158                              (list class)
1159                              (make-reader-method-function class slot-name)
1160                              (or slot-documentation "automatically generated reader method")
1161                              :slot-name slot-name
1162                              :object-class class
1163                              :method-class-function #'reader-method-class)))
1164
1165 (defmethod writer-method-class ((class slot-class) direct-slot &rest initargs)
1166   (declare (ignore direct-slot initargs))
1167   (find-class 'standard-writer-method))
1168
1169 (defmethod add-writer-method ((class slot-class) generic-function slot-name slot-documentation)
1170   (add-method generic-function
1171               (make-a-method 'standard-writer-method
1172                              ()
1173                              (list 'new-value (or (class-name class) 'object))
1174                              (list *the-class-t* class)
1175                              (make-writer-method-function class slot-name)
1176                              (or slot-documentation "automatically generated writer method")
1177                              :slot-name slot-name
1178                              :object-class class
1179                              :method-class-function #'writer-method-class)))
1180
1181 (defmethod add-boundp-method ((class slot-class) generic-function slot-name slot-documentation)
1182   (add-method generic-function
1183               (make-a-method (constantly (find-class 'standard-boundp-method))
1184                              class
1185                              ()
1186                              (list (or (class-name class) 'object))
1187                              (list class)
1188                              (make-boundp-method-function class slot-name)
1189                              (or slot-documentation "automatically generated boundp method")
1190                              slot-name)))
1191
1192 (defmethod remove-reader-method ((class slot-class) generic-function)
1193   (let ((method (get-method generic-function () (list class) nil)))
1194     (when method (remove-method generic-function method))))
1195
1196 (defmethod remove-writer-method ((class slot-class) generic-function)
1197   (let ((method
1198           (get-method generic-function () (list *the-class-t* class) nil)))
1199     (when method (remove-method generic-function method))))
1200
1201 (defmethod remove-boundp-method ((class slot-class) generic-function)
1202   (let ((method (get-method generic-function () (list class) nil)))
1203     (when method (remove-method generic-function method))))
1204 \f
1205 ;;; MAKE-READER-METHOD-FUNCTION and MAKE-WRITER-METHOD-FUNCTION
1206 ;;; function are NOT part of the standard protocol. They are however
1207 ;;; useful; PCL makes use of them internally and documents them for
1208 ;;; PCL users.  (FIXME: but SBCL certainly doesn't)
1209 ;;;
1210 ;;; *** This needs work to make type testing by the writer functions which
1211 ;;; *** do type testing faster. The idea would be to have one constructor
1212 ;;; *** for each possible type test.
1213 ;;;
1214 ;;; *** There is a subtle bug here which is going to have to be fixed.
1215 ;;; *** Namely, the simplistic use of the template has to be fixed. We
1216 ;;; *** have to give the OPTIMIZE-SLOT-VALUE method the user might have
1217 ;;; *** defined for this metaclass a chance to run.
1218
1219 (defmethod make-reader-method-function ((class slot-class) slot-name)
1220   (make-std-reader-method-function class slot-name))
1221
1222 (defmethod make-writer-method-function ((class slot-class) slot-name)
1223   (make-std-writer-method-function class slot-name))
1224
1225 (defmethod make-boundp-method-function ((class slot-class) slot-name)
1226   (make-std-boundp-method-function class slot-name))
1227 \f
1228 (defmethod compatible-meta-class-change-p (class proto-new-class)
1229   (eq (class-of class) (class-of proto-new-class)))
1230
1231 (defmethod validate-superclass ((class class) (superclass class))
1232   (or (eq superclass *the-class-t*)
1233       (eq (class-of class) (class-of superclass))
1234       (and (eq (class-of superclass) *the-class-standard-class*)
1235            (eq (class-of class) *the-class-funcallable-standard-class*))
1236       (and (eq (class-of superclass) *the-class-funcallable-standard-class*)
1237            (eq (class-of class) *the-class-standard-class*))))
1238 \f
1239 ;;; What this does depends on which of the four possible values of
1240 ;;; LAYOUT-INVALID the PCL wrapper has; the simplest case is when it
1241 ;;; is (:FLUSH <wrapper>) or (:OBSOLETE <wrapper>), when there is
1242 ;;; nothing to do, as the new wrapper has already been created.  If
1243 ;;; LAYOUT-INVALID returns NIL, then we invalidate it (setting it to
1244 ;;; (:FLUSH <wrapper>); UPDATE-SLOTS later gets to choose whether or
1245 ;;; not to "upgrade" this to (:OBSOLETE <wrapper>).
1246 ;;;
1247 ;;; This leaves the case where LAYOUT-INVALID returns T, which happens
1248 ;;; when REGISTER-LAYOUT has invalidated a superclass of CLASS (which
1249 ;;; invalidated all the subclasses in SB-KERNEL land).  Again, here we
1250 ;;; must flush the caches and allow UPDATE-SLOTS to decide whether to
1251 ;;; obsolete the wrapper.
1252 ;;;
1253 ;;; FIXME: either here or in INVALID-WRAPPER-P looks like a good place
1254 ;;; for (AVER (NOT (EQ (LAYOUT-INVALID OWRAPPER)
1255 ;;;                    :UNINITIALIZED)))
1256 ;;;
1257 ;;; Thanks to Gerd Moellmann for the explanation.  -- CSR, 2002-10-29
1258 (defun force-cache-flushes (class)
1259   (let* ((owrapper (class-wrapper class)))
1260     ;; We only need to do something if the wrapper is still valid. If
1261     ;; the wrapper isn't valid, state will be FLUSH or OBSOLETE, and
1262     ;; both of those will already be doing what we want. In
1263     ;; particular, we must be sure we never change an OBSOLETE into a
1264     ;; FLUSH since OBSOLETE means do what FLUSH does and then some.
1265     (when (or (not (invalid-wrapper-p owrapper))
1266               ;; KLUDGE: despite the observations above, this remains
1267               ;; a violation of locality or what might be considered
1268               ;; good style.  There has to be a better way!  -- CSR,
1269               ;; 2002-10-29
1270               (eq (layout-invalid owrapper) t))
1271       (let ((nwrapper (make-wrapper (layout-length owrapper)
1272                                     class)))
1273         (setf (wrapper-instance-slots-layout nwrapper)
1274               (wrapper-instance-slots-layout owrapper))
1275         (setf (wrapper-class-slots nwrapper)
1276               (wrapper-class-slots owrapper))
1277         (with-pcl-lock
1278           (update-lisp-class-layout class nwrapper)
1279           (setf (slot-value class 'wrapper) nwrapper)
1280           ;; Use :OBSOLETE instead of :FLUSH if any superclass has
1281           ;; been obsoleted.
1282           (if (find-if (lambda (x)
1283                          (and (consp x) (eq :obsolete (car x))))
1284                        (layout-inherits owrapper)
1285                        :key #'layout-invalid)
1286               (invalidate-wrapper owrapper :obsolete nwrapper)
1287               (invalidate-wrapper owrapper :flush nwrapper)))))))
1288
1289 (defun flush-cache-trap (owrapper nwrapper instance)
1290   (declare (ignore owrapper))
1291   (set-wrapper instance nwrapper))
1292 \f
1293 ;;; MAKE-INSTANCES-OBSOLETE can be called by user code. It will cause
1294 ;;; the next access to the instance (as defined in 88-002R) to trap
1295 ;;; through the UPDATE-INSTANCE-FOR-REDEFINED-CLASS mechanism.
1296 (defmethod make-instances-obsolete ((class std-class))
1297   (let* ((owrapper (class-wrapper class))
1298          (nwrapper (make-wrapper (layout-length owrapper)
1299                                  class)))
1300     (unless (class-finalized-p class)
1301       (if (class-has-a-forward-referenced-superclass-p class)
1302           (return-from make-instances-obsolete class)
1303           (update-cpl class (compute-class-precedence-list class))))
1304     (setf (wrapper-instance-slots-layout nwrapper)
1305           (wrapper-instance-slots-layout owrapper))
1306     (setf (wrapper-class-slots nwrapper)
1307           (wrapper-class-slots owrapper))
1308     (with-pcl-lock
1309         (update-lisp-class-layout class nwrapper)
1310       (setf (slot-value class 'wrapper) nwrapper)
1311       (invalidate-wrapper owrapper :obsolete nwrapper)
1312       class)))
1313
1314 (defmethod make-instances-obsolete ((class symbol))
1315   (make-instances-obsolete (find-class class))
1316   ;; ANSI wants the class name when called with a symbol.
1317   class)
1318
1319 ;;; OBSOLETE-INSTANCE-TRAP is the internal trap that is called when we
1320 ;;; see an obsolete instance. The times when it is called are:
1321 ;;;   - when the instance is involved in method lookup
1322 ;;;   - when attempting to access a slot of an instance
1323 ;;;
1324 ;;; It is not called by class-of, wrapper-of, or any of the low-level
1325 ;;; instance access macros.
1326 ;;;
1327 ;;; Of course these times when it is called are an internal
1328 ;;; implementation detail of PCL and are not part of the documented
1329 ;;; description of when the obsolete instance update happens. The
1330 ;;; documented description is as it appears in 88-002R.
1331 ;;;
1332 ;;; This has to return the new wrapper, so it counts on all the
1333 ;;; methods on obsolete-instance-trap-internal to return the new
1334 ;;; wrapper. It also does a little internal error checking to make
1335 ;;; sure that the traps are only happening when they should, and that
1336 ;;; the trap methods are computing appropriate new wrappers.
1337
1338 ;;; OBSOLETE-INSTANCE-TRAP might be called on structure instances
1339 ;;; after a structure is redefined. In most cases,
1340 ;;; OBSOLETE-INSTANCE-TRAP will not be able to fix the old instance,
1341 ;;; so it must signal an error. The hard part of this is that the
1342 ;;; error system and debugger might cause OBSOLETE-INSTANCE-TRAP to be
1343 ;;; called again, so in that case, we have to return some reasonable
1344 ;;; wrapper, instead.
1345
1346 (defvar *in-obsolete-instance-trap* nil)
1347 (defvar *the-wrapper-of-structure-object*
1348   (class-wrapper (find-class 'structure-object)))
1349
1350 (define-condition obsolete-structure (error)
1351   ((datum :reader obsolete-structure-datum :initarg :datum))
1352   (:report
1353    (lambda (condition stream)
1354      ;; Don't try to print the structure, since it probably won't work.
1355      (format stream
1356              "~@<obsolete structure error for a structure of type ~2I~_~S~:>"
1357              (type-of (obsolete-structure-datum condition))))))
1358
1359 (defun obsolete-instance-trap (owrapper nwrapper instance)
1360   (if (not (pcl-instance-p instance))
1361       (if *in-obsolete-instance-trap*
1362           *the-wrapper-of-structure-object*
1363            (let ((*in-obsolete-instance-trap* t))
1364              (error 'obsolete-structure :datum instance)))
1365       (let* ((class (wrapper-class* nwrapper))
1366              (copy (allocate-instance class)) ;??? allocate-instance ???
1367              (olayout (wrapper-instance-slots-layout owrapper))
1368              (nlayout (wrapper-instance-slots-layout nwrapper))
1369              (oslots (get-slots instance))
1370              (nslots (get-slots copy))
1371              (oclass-slots (wrapper-class-slots owrapper))
1372              (added ())
1373              (discarded ())
1374              (plist ()))
1375
1376         ;; local  --> local     transfer value
1377         ;; local  --> shared    discard value, discard slot
1378         ;; local  -->  --       discard slot
1379         ;; shared --> local     transfer value
1380         ;; shared --> shared    -- (cf SHARED-INITIALIZE :AFTER STD-CLASS)
1381         ;; shared -->  --       discard value
1382         ;;  --    --> local     add slot
1383         ;;  --    --> shared    --
1384
1385         ;; Go through all the old local slots.
1386         (let ((opos 0))
1387           (dolist (name olayout)
1388             (let ((npos (posq name nlayout)))
1389               (if npos
1390                   (setf (clos-slots-ref nslots npos)
1391                         (clos-slots-ref oslots opos))
1392                   (progn
1393                     (push name discarded)
1394                     (unless (eq (clos-slots-ref oslots opos) +slot-unbound+)
1395                       (setf (getf plist name) (clos-slots-ref oslots opos))))))
1396             (incf opos)))
1397
1398         ;; Go through all the old shared slots.
1399         (dolist (oclass-slot-and-val oclass-slots)
1400           (let ((name (car oclass-slot-and-val))
1401                 (val (cdr oclass-slot-and-val)))
1402             (let ((npos (posq name nlayout)))
1403               (when npos
1404                 (setf (clos-slots-ref nslots npos) val)))))
1405
1406         ;; Go through all the new local slots to compute the added slots.
1407         (dolist (nlocal nlayout)
1408           (unless (or (memq nlocal olayout)
1409                       (assq nlocal oclass-slots))
1410             (push nlocal added)))
1411
1412         (swap-wrappers-and-slots instance copy)
1413
1414         (update-instance-for-redefined-class instance
1415                                              added
1416                                              discarded
1417                                              plist)
1418         nwrapper)))
1419 \f
1420 (defun change-class-internal (instance new-class initargs)
1421   (let* ((old-class (class-of instance))
1422          (copy (allocate-instance new-class))
1423          (new-wrapper (get-wrapper copy))
1424          (old-wrapper (class-wrapper old-class))
1425          (old-layout (wrapper-instance-slots-layout old-wrapper))
1426          (new-layout (wrapper-instance-slots-layout new-wrapper))
1427          (old-slots (get-slots instance))
1428          (new-slots (get-slots copy))
1429          (old-class-slots (wrapper-class-slots old-wrapper)))
1430
1431     ;; "The values of local slots specified by both the class CTO and
1432     ;; CFROM are retained. If such a local slot was unbound, it
1433     ;; remains unbound."
1434     (let ((new-position 0))
1435       (dolist (new-slot new-layout)
1436         (let ((old-position (posq new-slot old-layout)))
1437           (when old-position
1438             (setf (clos-slots-ref new-slots new-position)
1439                   (clos-slots-ref old-slots old-position))))
1440         (incf new-position)))
1441
1442     ;; "The values of slots specified as shared in the class CFROM and
1443     ;; as local in the class CTO are retained."
1444     (dolist (slot-and-val old-class-slots)
1445       (let ((position (posq (car slot-and-val) new-layout)))
1446         (when position
1447           (setf (clos-slots-ref new-slots position) (cdr slot-and-val)))))
1448
1449     ;; Make the copy point to the old instance's storage, and make the
1450     ;; old instance point to the new storage.
1451     (swap-wrappers-and-slots instance copy)
1452
1453     (apply #'update-instance-for-different-class copy instance initargs)
1454     instance))
1455
1456 (defmethod change-class ((instance standard-object) (new-class standard-class)
1457                          &rest initargs)
1458   (unless (class-finalized-p new-class)
1459     (finalize-inheritance new-class))
1460   (let ((cpl (class-precedence-list new-class)))
1461     (dolist (class cpl)
1462       (macrolet
1463           ((frob (class-name)
1464              `(when (eq class (find-class ',class-name))
1465                (error 'metaobject-initialization-violation
1466                 :format-control "~@<Cannot ~S objects into ~S metaobjects.~@:>"
1467                 :format-arguments (list 'change-class ',class-name)
1468                 :references (list '(:amop :initialization ,class-name))))))
1469         (frob class)
1470         (frob generic-function)
1471         (frob method)
1472         (frob slot-definition))))
1473   (change-class-internal instance new-class initargs))
1474
1475 (defmethod change-class ((instance forward-referenced-class)
1476                          (new-class standard-class) &rest initargs)
1477   (let ((cpl (class-precedence-list new-class)))
1478     (dolist (class cpl
1479              (error 'metaobject-initialization-violation
1480                     :format-control
1481                     "~@<Cannot ~S ~S objects into non-~S objects.~@:>"
1482                     :format-arguments
1483                     (list 'change-class 'forward-referenced-class 'class)
1484                     :references
1485                     (list '(:amop :generic-function ensure-class-using-class)
1486                           '(:amop :initialization class))))
1487       (when (eq class (find-class 'class))
1488         (return nil))))
1489   (change-class-internal instance new-class initargs))
1490
1491 (defmethod change-class ((instance funcallable-standard-object)
1492                          (new-class funcallable-standard-class)
1493                          &rest initargs)
1494   (let ((cpl (class-precedence-list new-class)))
1495     (dolist (class cpl)
1496       (macrolet
1497           ((frob (class-name)
1498              `(when (eq class (find-class ',class-name))
1499                (error 'metaobject-initialization-violation
1500                 :format-control "~@<Cannot ~S objects into ~S metaobjects.~@:>"
1501                 :format-arguments (list 'change-class ',class-name)
1502                 :references (list '(:amop :initialization ,class-name))))))
1503         (frob class)
1504         (frob generic-function)
1505         (frob method)
1506         (frob slot-definition))))
1507   (change-class-internal instance new-class initargs))
1508
1509 (defmethod change-class ((instance standard-object)
1510                          (new-class funcallable-standard-class)
1511                          &rest initargs)
1512   (declare (ignore initargs))
1513   (error "You can't change the class of ~S to ~S~@
1514           because it isn't already an instance with metaclass ~S."
1515          instance new-class 'standard-class))
1516
1517 (defmethod change-class ((instance funcallable-standard-object)
1518                          (new-class standard-class)
1519                          &rest initargs)
1520   (declare (ignore initargs))
1521   (error "You can't change the class of ~S to ~S~@
1522           because it isn't already an instance with metaclass ~S."
1523          instance new-class 'funcallable-standard-class))
1524
1525 (defmethod change-class ((instance t) (new-class-name symbol) &rest initargs)
1526   (apply #'change-class instance (find-class new-class-name) initargs))
1527 \f
1528 ;;;; The metaclass BUILT-IN-CLASS
1529 ;;;;
1530 ;;;; This metaclass is something of a weird creature. By this point, all
1531 ;;;; instances of it which will exist have been created, and no instance
1532 ;;;; is ever created by calling MAKE-INSTANCE.
1533 ;;;;
1534 ;;;; But, there are other parts of the protocol we must follow and those
1535 ;;;; definitions appear here.
1536
1537 (macrolet ((def (name args control)
1538                `(defmethod ,name ,args
1539                  (declare (ignore initargs))
1540                  (error 'metaobject-initialization-violation
1541                   :format-control ,(format nil "~@<~A~@:>" control)
1542                   :format-arguments (list ',name)
1543                   :references (list '(:amop :initialization "Class"))))))
1544   (def initialize-instance ((class built-in-class) &rest initargs)
1545     "Cannot ~S an instance of BUILT-IN-CLASS.")
1546   (def reinitialize-instance ((class built-in-class) &rest initargs)
1547     "Cannot ~S an instance of BUILT-IN-CLASS."))
1548
1549 (macrolet ((def (name)
1550                `(defmethod ,name ((class built-in-class)) nil)))
1551   (def class-direct-slots)
1552   (def class-slots)
1553   (def class-direct-default-initargs)
1554   (def class-default-initargs))
1555
1556 (defmethod validate-superclass ((c class) (s built-in-class))
1557   (or (eq s *the-class-t*) (eq s *the-class-stream*)
1558       ;; FIXME: bad things happen if someone tries to mix in both
1559       ;; FILE-STREAM and STRING-STREAM (as they have the same
1560       ;; layout-depthoid).  Is there any way we can provide a useful
1561       ;; error message?  -- CSR, 2005-05-03
1562       (eq s *the-class-file-stream*) (eq s *the-class-string-stream*)
1563       ;; This probably shouldn't be mixed in with certain other
1564       ;; classes, too, but it seems to work both with STANDARD-OBJECT
1565       ;; and FUNCALLABLE-STANDARD-OBJECT
1566       (eq s *the-class-sequence*)))
1567 \f
1568 ;;; Some necessary methods for FORWARD-REFERENCED-CLASS
1569 (defmethod class-direct-slots ((class forward-referenced-class)) ())
1570 (defmethod class-direct-default-initargs ((class forward-referenced-class)) ())
1571 (macrolet ((def (method)
1572              `(defmethod ,method ((class forward-referenced-class))
1573                 (error "~@<~I~S was called on a forward referenced class:~2I~_~S~:>"
1574                        ',method class))))
1575   (def class-default-initargs)
1576   (def class-precedence-list)
1577   (def class-slots))
1578
1579 (defmethod validate-superclass ((c slot-class)
1580                                 (f forward-referenced-class))
1581   t)
1582 \f
1583 (defmethod add-dependent ((metaobject dependent-update-mixin) dependent)
1584   (pushnew dependent (plist-value metaobject 'dependents)))
1585
1586 (defmethod remove-dependent ((metaobject dependent-update-mixin) dependent)
1587   (setf (plist-value metaobject 'dependents)
1588         (delete dependent (plist-value metaobject 'dependents))))
1589
1590 (defmethod map-dependents ((metaobject dependent-update-mixin) function)
1591   (dolist (dependent (plist-value metaobject 'dependents))
1592     (funcall function dependent)))
1593