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