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