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