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