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