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