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