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