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