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