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