b7ada1fc57e895ffc2b8372c431d5ebbe990b236
[sbcl.git] / src / code / class.lisp
1 ;;;; This file contains structures and functions for the maintenance of
2 ;;;; basic information about defined types. Different object systems
3 ;;;; can be supported simultaneously.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!KERNEL")
15
16 (!begin-collecting-cold-init-forms)
17 \f
18 ;;;; the CLASSOID structure
19
20 ;;; The CLASSOID structure is a supertype of all classoid types.  A
21 ;;; CLASSOID is also a CTYPE structure as recognized by the type
22 ;;; system.  (FIXME: It's also a type specifier, though this might go
23 ;;; away as with the merger of SB-PCL:CLASS and CL:CLASS it's no
24 ;;; longer necessary)
25 (def!struct (classoid
26              (:make-load-form-fun classoid-make-load-form-fun)
27              (:include ctype
28                        (class-info (type-class-or-lose 'classoid)))
29              (:constructor nil)
30              #-no-ansi-print-object
31              (:print-object
32               (lambda (class stream)
33                 (let ((name (classoid-name class)))
34                   (print-unreadable-object (class stream
35                                                   :type t
36                                                   :identity (not name))
37                     (format stream
38                             ;; FIXME: Make sure that this prints
39                             ;; reasonably for anonymous classes.
40                             "~:[anonymous~;~:*~S~]~@[ (~(~A~))~]"
41                             name
42                             (classoid-state class))))))
43              #-sb-xc-host (:pure nil))
44   ;; the value to be returned by CLASSOID-NAME.
45   (name nil :type symbol)
46   ;; the current layout for this class, or NIL if none assigned yet
47   (layout nil :type (or layout null))
48   ;; How sure are we that this class won't be redefined?
49   ;;   :READ-ONLY = We are committed to not changing the effective
50   ;;                slots or superclasses.
51   ;;   :SEALED    = We can't even add subclasses.
52   ;;   NIL        = Anything could happen.
53   (state nil :type (member nil :read-only :sealed))
54   ;; direct superclasses of this class
55   (direct-superclasses () :type list)
56   ;; representation of all of the subclasses (direct or indirect) of
57   ;; this class. This is NIL if no subclasses or not initalized yet;
58   ;; otherwise, it's an EQ hash-table mapping CLASSOID objects to the
59   ;; subclass layout that was in effect at the time the subclass was
60   ;; created.
61   (subclasses nil :type (or null hash-table))
62   ;; the PCL class (= CL:CLASS, but with a view to future flexibility
63   ;; we don't just call it the CLASS slot) object for this class, or
64   ;; NIL if none assigned yet
65   (pcl-class nil))
66
67 (defun classoid-make-load-form-fun (class)
68   (/show "entering CLASSOID-MAKE-LOAD-FORM-FUN" class)
69   (let ((name (classoid-name class)))
70     (unless (and name (eq (find-classoid name nil) class))
71       (/show "anonymous/undefined class case")
72       (error "can't use anonymous or undefined class as constant:~%  ~S"
73              class))
74     `(locally
75        ;; KLUDGE: There's a FIND-CLASSOID DEFTRANSFORM for constant
76        ;; class names which creates fast but non-cold-loadable,
77        ;; non-compact code. In this context, we'd rather have compact,
78        ;; cold-loadable code. -- WHN 19990928
79        (declare (notinline find-classoid))
80        (find-classoid ',name))))
81 \f
82 ;;;; basic LAYOUT stuff
83
84 ;;; Note: This bound is set somewhat less than MOST-POSITIVE-FIXNUM
85 ;;; in order to guarantee that several hash values can be added without
86 ;;; overflowing into a bignum.
87 (def!constant layout-clos-hash-limit (1+ (ash sb!xc:most-positive-fixnum -3))
88   #!+sb-doc
89   "the exclusive upper bound on LAYOUT-CLOS-HASH values")
90 (def!type layout-clos-hash () '(integer 0 #.layout-clos-hash-limit))
91
92 ;;; a list of conses, initialized by genesis
93 ;;;
94 ;;; In each cons, the car is the symbol naming the layout, and the
95 ;;; cdr is the layout itself.
96 (defvar *!initial-layouts*)
97
98 ;;; a table mapping class names to layouts for classes we have
99 ;;; referenced but not yet loaded. This is initialized from an alist
100 ;;; created by genesis describing the layouts that genesis created at
101 ;;; cold-load time.
102 (defvar *forward-referenced-layouts*)
103 (!cold-init-forms
104   (setq *forward-referenced-layouts* (make-hash-table :test 'equal))
105   #-sb-xc-host (progn
106                  (/show0 "processing *!INITIAL-LAYOUTS*")
107                  (dolist (x *!initial-layouts*)
108                    (setf (gethash (car x) *forward-referenced-layouts*)
109                          (cdr x)))
110                  (/show0 "done processing *!INITIAL-LAYOUTS*")))
111
112 ;;; The LAYOUT structure is pointed to by the first cell of instance
113 ;;; (or structure) objects. It represents what we need to know for
114 ;;; type checking and garbage collection. Whenever a class is
115 ;;; incompatibly redefined, a new layout is allocated. If two object's
116 ;;; layouts are EQ, then they are exactly the same type.
117 (def!struct (layout
118              ;; KLUDGE: A special hack keeps this from being
119              ;; called when building code for the
120              ;; cross-compiler. See comments at the DEFUN for
121              ;; this. -- WHN 19990914
122              (:make-load-form-fun #-sb-xc-host ignore-it
123                                   ;; KLUDGE: DEF!STRUCT at #+SB-XC-HOST
124                                   ;; time controls both the
125                                   ;; build-the-cross-compiler behavior
126                                   ;; and the run-the-cross-compiler
127                                   ;; behavior. The value below only
128                                   ;; works for build-the-cross-compiler.
129                                   ;; There's a special hack in
130                                   ;; EMIT-MAKE-LOAD-FORM which gives
131                                   ;; effectively IGNORE-IT behavior for
132                                   ;; LAYOUT at run-the-cross-compiler
133                                   ;; time. It would be cleaner to
134                                   ;; actually have an IGNORE-IT value
135                                   ;; stored, but it's hard to see how to
136                                   ;; do that concisely with the current
137                                   ;; DEF!STRUCT setup. -- WHN 19990930
138                                   #+sb-xc-host
139                                   make-load-form-for-layout))
140   ;; a pseudo-random hash value for use by CLOS.  KLUDGE: The fact
141   ;; that this slot is at offset 1 is known to GENESIS.
142   (clos-hash (random-layout-clos-hash) :type layout-clos-hash)
143   ;; the class that this is a layout for
144   (classoid (missing-arg) :type classoid)
145   ;; The value of this slot can be:
146   ;;   * :UNINITIALIZED if not initialized yet;
147   ;;   * NIL if this is the up-to-date layout for a class; or
148   ;;   * T if this layout has been invalidated (by being replaced by
149   ;;     a new, more-up-to-date LAYOUT).
150   ;;   * something else (probably a list) if the class is a PCL wrapper
151   ;;     and PCL has made it invalid and made a note to itself about it
152   (invalid :uninitialized :type (or cons (member nil t :uninitialized)))
153   ;; the layouts for all classes we inherit. If hierarchical, i.e. if
154   ;; DEPTHOID >= 0, then these are ordered by ORDER-LAYOUT-INHERITS
155   ;; (least to most specific), so that each inherited layout appears
156   ;; at its expected depth, i.e. at its LAYOUT-DEPTHOID value.
157   ;;
158   ;; Remaining elements are filled by the non-hierarchical layouts or,
159   ;; if they would otherwise be empty, by copies of succeeding layouts.
160   (inherits #() :type simple-vector)
161   ;; If inheritance is not hierarchical, this is -1. If inheritance is
162   ;; hierarchical, this is the inheritance depth, i.e. (LENGTH INHERITS).
163   ;; Note:
164   ;;  (1) This turns out to be a handy encoding for arithmetically
165   ;;      comparing deepness; it is generally useful to do a bare numeric
166   ;;      comparison of these depthoid values, and we hardly ever need to
167   ;;      test whether the values are negative or not.
168   ;;  (2) This was called INHERITANCE-DEPTH in classic CMU CL. It was
169   ;;      renamed because some of us find it confusing to call something
170   ;;      a depth when it isn't quite.
171   (depthoid -1 :type layout-depthoid)
172   ;; the number of top level descriptor cells in each instance
173   (length 0 :type index)
174   ;; If this layout has some kind of compiler meta-info, then this is
175   ;; it. If a structure, then we store the DEFSTRUCT-DESCRIPTION here.
176   (info nil)
177   ;; This is true if objects of this class are never modified to
178   ;; contain dynamic pointers in their slots or constant-like
179   ;; substructure (and hence can be copied into read-only space by
180   ;; PURIFY).
181   ;;
182   ;; This slot is known to the C runtime support code.
183   (pure nil :type (member t nil 0))
184   ;; Number of raw words at the end.
185   ;; This slot is known to the C runtime support code.
186   (n-untagged-slots 0 :type index)
187   ;; Definition location
188   (source-location nil)
189   ;; True IFF the layout belongs to a standand-instance or a
190   ;; standard-funcallable-instance -- that is, true only if the layout
191   ;; is really a wrapper.
192   ;;
193   ;; FIXME: If we unify wrappers and layouts this can go away, since
194   ;; it is only used in SB-PCL::EMIT-FETCH-WRAPPERS, which can then
195   ;; use INSTANCE-SLOTS-LAYOUT instead (if there is are no slot
196   ;; layouts, there are no slots for it to pull.)
197   (for-std-class-p nil :type boolean :read-only t))
198
199 (def!method print-object ((layout layout) stream)
200   (print-unreadable-object (layout stream :type t :identity t)
201     (format stream
202             "for ~S~@[, INVALID=~S~]"
203             (layout-proper-name layout)
204             (layout-invalid layout))))
205
206 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
207   (defun layout-proper-name (layout)
208     (classoid-proper-name (layout-classoid layout))))
209 \f
210 ;;;; support for the hash values used by CLOS when working with LAYOUTs
211
212 ;;; a generator for random values suitable for the CLOS-HASH slots of
213 ;;; LAYOUTs. We use our own RANDOM-STATE here because we'd like
214 ;;; pseudo-random values to come the same way in the target even when
215 ;;; we make minor changes to the system, in order to reduce the
216 ;;; mysteriousness of possible CLOS bugs.
217 (defvar *layout-clos-hash-random-state*)
218 (defun random-layout-clos-hash ()
219   ;; FIXME: I'm not sure why this expression is (1+ (RANDOM FOO)),
220   ;; returning a strictly positive value. I copied it verbatim from
221   ;; CMU CL INITIALIZE-LAYOUT-HASH, so presumably it works, but I
222   ;; dunno whether the hash values are really supposed to be 1-based.
223   ;; They're declared as INDEX.. Or is this a hack to try to avoid
224   ;; having to use bignum arithmetic? Or what? An explanation would be
225   ;; nice.
226   ;;
227   ;; an explanation is provided in Kiczales and Rodriguez, "Efficient
228   ;; Method Dispatch in PCL", 1990.  -- CSR, 2005-11-30
229   (1+ (random (1- layout-clos-hash-limit)
230               (if (boundp '*layout-clos-hash-random-state*)
231                   *layout-clos-hash-random-state*
232                   (setf *layout-clos-hash-random-state*
233                         (make-random-state))))))
234 \f
235 ;;; If we can't find any existing layout, then we create a new one
236 ;;; storing it in *FORWARD-REFERENCED-LAYOUTS*. In classic CMU CL, we
237 ;;; used to immediately check for compatibility, but for
238 ;;; cross-compilability reasons (i.e. convenience of using this
239 ;;; function in a MAKE-LOAD-FORM expression) that functionality has
240 ;;; been split off into INIT-OR-CHECK-LAYOUT.
241 (declaim (ftype (function (symbol) layout) find-layout))
242 (defun find-layout (name)
243   (let ((classoid (find-classoid name nil)))
244     (or (and classoid (classoid-layout classoid))
245         (gethash name *forward-referenced-layouts*)
246         (setf (gethash name *forward-referenced-layouts*)
247               (make-layout :classoid (or classoid
248                                          (make-undefined-classoid name)))))))
249
250 ;;; If LAYOUT is uninitialized, initialize it with CLASSOID, LENGTH,
251 ;;; INHERITS, and DEPTHOID, otherwise require that it be consistent
252 ;;; with CLASSOID, LENGTH, INHERITS, and DEPTHOID.
253 ;;;
254 ;;; UNDEFINED-CLASS values are interpreted specially as "we don't know
255 ;;; anything about the class", so if LAYOUT is initialized, any
256 ;;; preexisting class slot value is OK, and if it's not initialized,
257 ;;; its class slot value is set to an UNDEFINED-CLASS. -- FIXME: This
258 ;;; is no longer true, :UNINITIALIZED used instead.
259 (declaim (ftype (function (layout classoid index simple-vector layout-depthoid
260                                   index)
261                           layout)
262                 init-or-check-layout))
263 (defun init-or-check-layout
264     (layout classoid length inherits depthoid nuntagged)
265   (cond ((eq (layout-invalid layout) :uninitialized)
266          ;; There was no layout before, we just created one which
267          ;; we'll now initialize with our information.
268          (setf (layout-length layout) length
269                (layout-inherits layout) inherits
270                (layout-depthoid layout) depthoid
271                (layout-n-untagged-slots layout) nuntagged
272                (layout-classoid layout) classoid
273                (layout-invalid layout) nil))
274         ;; FIXME: Now that LAYOUTs are born :UNINITIALIZED, maybe this
275         ;; clause is not needed?
276         ((not *type-system-initialized*)
277          (setf (layout-classoid layout) classoid))
278         (t
279          ;; There was an old layout already initialized with old
280          ;; information, and we'll now check that old information
281          ;; which was known with certainty is consistent with current
282          ;; information which is known with certainty.
283          (check-layout layout classoid length inherits depthoid nuntagged)))
284   layout)
285
286 ;;; In code for the target Lisp, we don't use dump LAYOUTs using the
287 ;;; standard load form mechanism, we use special fops instead, in
288 ;;; order to make cold load come out right. But when we're building
289 ;;; the cross-compiler, we can't do that because we don't have access
290 ;;; to special non-ANSI low-level things like special fops, and we
291 ;;; don't need to do that anyway because our code isn't going to be
292 ;;; cold loaded, so we use the ordinary load form system.
293 ;;;
294 ;;; KLUDGE: A special hack causes this not to be called when we are
295 ;;; building code for the target Lisp. It would be tidier to just not
296 ;;; have it in place when we're building the target Lisp, but it
297 ;;; wasn't clear how to do that without rethinking DEF!STRUCT quite a
298 ;;; bit, so I punted. -- WHN 19990914
299 #+sb-xc-host
300 (defun make-load-form-for-layout (layout &optional env)
301   (declare (type layout layout))
302   (declare (ignore env))
303   (when (layout-invalid layout)
304     (compiler-error "can't dump reference to obsolete class: ~S"
305                     (layout-classoid layout)))
306   (let ((name (classoid-name (layout-classoid layout))))
307     (unless name
308       (compiler-error "can't dump anonymous LAYOUT: ~S" layout))
309     ;; Since LAYOUT refers to a class which refers back to the LAYOUT,
310     ;; we have to do this in two stages, like the TREE-WITH-PARENT
311     ;; example in the MAKE-LOAD-FORM entry in the ANSI spec.
312     (values
313      ;; "creation" form (which actually doesn't create a new LAYOUT if
314      ;; there's a preexisting one with this name)
315      `(find-layout ',name)
316      ;; "initialization" form (which actually doesn't initialize
317      ;; preexisting LAYOUTs, just checks that they're consistent).
318      `(init-or-check-layout ',layout
319                             ',(layout-classoid layout)
320                             ',(layout-length layout)
321                             ',(layout-inherits layout)
322                             ',(layout-depthoid layout)
323                             ',(layout-n-untagged-slots layout)))))
324
325 ;;; If LAYOUT's slot values differ from the specified slot values in
326 ;;; any interesting way, then give a warning and return T.
327 (declaim (ftype (function (simple-string
328                            layout
329                            simple-string
330                            index
331                            simple-vector
332                            layout-depthoid
333                            index))
334                 redefine-layout-warning))
335 (defun redefine-layout-warning (old-context old-layout
336                                 context length inherits depthoid nuntagged)
337   (declare (type layout old-layout) (type simple-string old-context context))
338   (let ((name (layout-proper-name old-layout)))
339     (or (let ((old-inherits (layout-inherits old-layout)))
340           (or (when (mismatch old-inherits
341                               inherits
342                               :key #'layout-proper-name)
343                 (warn "change in superclasses of class ~S:~%  ~
344                        ~A superclasses: ~S~%  ~
345                        ~A superclasses: ~S"
346                       name
347                       old-context
348                       (map 'list #'layout-proper-name old-inherits)
349                       context
350                       (map 'list #'layout-proper-name inherits))
351                 t)
352               (let ((diff (mismatch old-inherits inherits)))
353                 (when diff
354                   (warn
355                    "in class ~S:~%  ~
356                     ~:(~A~) definition of superclass ~S is incompatible with~%  ~
357                     ~A definition."
358                    name
359                    old-context
360                    (layout-proper-name (svref old-inherits diff))
361                    context)
362                   t))))
363         (let ((old-length (layout-length old-layout)))
364           (unless (= old-length length)
365             (warn "change in instance length of class ~S:~%  ~
366                    ~A length: ~W~%  ~
367                    ~A length: ~W"
368                   name
369                   old-context old-length
370                   context length)
371             t))
372         (let ((old-nuntagged (layout-n-untagged-slots old-layout)))
373           (unless (= old-nuntagged nuntagged)
374             (warn "change in instance layout of class ~S:~%  ~
375                    ~A untagged slots: ~W~%  ~
376                    ~A untagged slots: ~W"
377                   name
378                   old-context old-nuntagged
379                   context nuntagged)
380             t))
381         (unless (= (layout-depthoid old-layout) depthoid)
382           (warn "change in the inheritance structure of class ~S~%  ~
383                  between the ~A definition and the ~A definition"
384                 name old-context context)
385           t))))
386
387 ;;; Require that LAYOUT data be consistent with CLASS, LENGTH,
388 ;;; INHERITS, and DEPTHOID.
389 (declaim (ftype (function
390                  (layout classoid index simple-vector layout-depthoid index))
391                 check-layout))
392 (defun check-layout (layout classoid length inherits depthoid nuntagged)
393   (aver (eq (layout-classoid layout) classoid))
394   (when (redefine-layout-warning "current" layout
395                                  "compile time" length inherits depthoid
396                                  nuntagged)
397     ;; Classic CMU CL had more options here. There are several reasons
398     ;; why they might want more options which are less appropriate for
399     ;; us: (1) It's hard to fit the classic CMU CL flexible approach
400     ;; into the ANSI-style MAKE-LOAD-FORM system, and having a
401     ;; non-MAKE-LOAD-FORM-style system is painful when we're trying to
402     ;; make the cross-compiler run under vanilla ANSI Common Lisp. (2)
403     ;; We have CLOS now, and if you want to be able to flexibly
404     ;; redefine classes without restarting the system, it'd make sense
405     ;; to use that, so supporting complexity in order to allow
406     ;; modifying DEFSTRUCTs without restarting the system is a low
407     ;; priority. (3) We now have the ability to rebuild the SBCL
408     ;; system from scratch, so we no longer need this functionality in
409     ;; order to maintain the SBCL system by modifying running images.
410     (error "The class ~S was not changed, and there's no guarantee that~@
411             the loaded code (which expected another layout) will work."
412            (layout-proper-name layout)))
413   (values))
414
415 ;;; a common idiom (the same as CMU CL FIND-LAYOUT) rolled up into a
416 ;;; single function call
417 ;;;
418 ;;; Used by the loader to forward-reference layouts for classes whose
419 ;;; definitions may not have been loaded yet. This allows type tests
420 ;;; to be loaded when the type definition hasn't been loaded yet.
421 (declaim (ftype (function (symbol index simple-vector layout-depthoid index)
422                           layout)
423                 find-and-init-or-check-layout))
424 (defun find-and-init-or-check-layout (name length inherits depthoid nuntagged)
425   (let ((layout (find-layout name)))
426     (init-or-check-layout layout
427                           (or (find-classoid name nil)
428                               (layout-classoid layout))
429                           length
430                           inherits
431                           depthoid
432                           nuntagged)))
433
434 ;;; Record LAYOUT as the layout for its class, adding it as a subtype
435 ;;; of all superclasses. This is the operation that "installs" a
436 ;;; layout for a class in the type system, clobbering any old layout.
437 ;;; However, this does not modify the class namespace; that is a
438 ;;; separate operation (think anonymous classes.)
439 ;;; -- If INVALIDATE, then all the layouts for any old definition
440 ;;;    and subclasses are invalidated, and the SUBCLASSES slot is cleared.
441 ;;; -- If DESTRUCT-LAYOUT, then this is some old layout, and is to be
442 ;;;    destructively modified to hold the same type information.
443 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
444 (defun register-layout (layout &key (invalidate t) destruct-layout)
445   (declare (type layout layout) (type (or layout null) destruct-layout))
446   (let* ((classoid (layout-classoid layout))
447          (classoid-layout (classoid-layout classoid))
448          (subclasses (classoid-subclasses classoid)))
449
450     ;; Attempting to register ourselves with a temporary undefined
451     ;; class placeholder is almost certainly a programmer error. (I
452     ;; should know, I did it.) -- WHN 19990927
453     (aver (not (undefined-classoid-p classoid)))
454
455     ;; This assertion dates from classic CMU CL. The rationale is
456     ;; probably that calling REGISTER-LAYOUT more than once for the
457     ;; same LAYOUT is almost certainly a programmer error.
458     (aver (not (eq classoid-layout layout)))
459
460     ;; Figure out what classes are affected by the change, and issue
461     ;; appropriate warnings and invalidations.
462     (when classoid-layout
463       (modify-classoid classoid)
464       (when subclasses
465         (dohash (subclass subclass-layout subclasses)
466           (modify-classoid subclass)
467           (when invalidate
468             (invalidate-layout subclass-layout))))
469       (when invalidate
470         (invalidate-layout classoid-layout)
471         (setf (classoid-subclasses classoid) nil)))
472
473     (if destruct-layout
474         (setf (layout-invalid destruct-layout) nil
475               (layout-inherits destruct-layout) (layout-inherits layout)
476               (layout-depthoid destruct-layout)(layout-depthoid layout)
477               (layout-length destruct-layout) (layout-length layout)
478               (layout-n-untagged-slots destruct-layout) (layout-n-untagged-slots layout)
479               (layout-info destruct-layout) (layout-info layout)
480               (classoid-layout classoid) destruct-layout)
481         (setf (layout-invalid layout) nil
482               (classoid-layout classoid) layout))
483
484     (dovector (super-layout (layout-inherits layout))
485       (let* ((super (layout-classoid super-layout))
486              (subclasses (or (classoid-subclasses super)
487                              (setf (classoid-subclasses super)
488                                    (make-hash-table :test 'eq)))))
489         (when (and (eq (classoid-state super) :sealed)
490                    (not (gethash classoid subclasses)))
491           (warn "unsealing sealed class ~S in order to subclass it"
492                 (classoid-name super))
493           (setf (classoid-state super) :read-only))
494         (setf (gethash classoid subclasses)
495               (or destruct-layout layout)))))
496
497   (values))
498 ); EVAL-WHEN
499
500 ;;; Arrange the inherited layouts to appear at their expected depth,
501 ;;; ensuring that hierarchical type tests succeed. Layouts with
502 ;;; DEPTHOID >= 0 (i.e. hierarchical classes) are placed first,
503 ;;; at exactly that index in the INHERITS vector. Then, non-hierarchical
504 ;;; layouts are placed in remaining elements. Then, any still-empty
505 ;;; elements are filled with their successors, ensuring that each
506 ;;; element contains a valid layout.
507 ;;;
508 ;;; This reordering may destroy CPL ordering, so the inherits should
509 ;;; not be read as being in CPL order.
510 (defun order-layout-inherits (layouts)
511   (declare (simple-vector layouts))
512   (let ((length (length layouts))
513         (max-depth -1))
514     (dotimes (i length)
515       (let ((depth (layout-depthoid (svref layouts i))))
516         (when (> depth max-depth)
517           (setf max-depth depth))))
518     (let* ((new-length (max (1+ max-depth) length))
519            ;; KLUDGE: 0 here is the "uninitialized" element.  We need
520            ;; to specify it explicitly for portability purposes, as
521            ;; elements can be read before being set [ see below, "(EQL
522            ;; OLD-LAYOUT 0)" ].  -- CSR, 2002-04-20
523            (inherits (make-array new-length :initial-element 0)))
524       (dotimes (i length)
525         (let* ((layout (svref layouts i))
526                (depth (layout-depthoid layout)))
527           (unless (eql depth -1)
528             (let ((old-layout (svref inherits depth)))
529               (unless (or (eql old-layout 0) (eq old-layout layout))
530                 (error "layout depth conflict: ~S~%" layouts)))
531             (setf (svref inherits depth) layout))))
532       (do ((i 0 (1+ i))
533            (j 0))
534           ((>= i length))
535         (declare (type index i j))
536         (let* ((layout (svref layouts i))
537                (depth (layout-depthoid layout)))
538           (when (eql depth -1)
539             (loop (when (eql (svref inherits j) 0)
540                     (return))
541                   (incf j))
542             (setf (svref inherits j) layout))))
543       (do ((i (1- new-length) (1- i)))
544           ((< i 0))
545         (declare (type fixnum i))
546         (when (eql (svref inherits i) 0)
547           (setf (svref inherits i) (svref inherits (1+ i)))))
548       inherits)))
549 \f
550 ;;;; class precedence lists
551
552 ;;; Topologically sort the list of objects to meet a set of ordering
553 ;;; constraints given by pairs (A . B) constraining A to precede B.
554 ;;; When there are multiple objects to choose, the tie-breaker
555 ;;; function is called with both the list of object to choose from and
556 ;;; the reverse ordering built so far.
557 (defun topological-sort (objects constraints tie-breaker)
558   (declare (list objects constraints)
559            (function tie-breaker))
560   (let ((obj-info (make-hash-table :size (length objects)))
561         (free-objs nil)
562         (result nil))
563     (dolist (constraint constraints)
564       (let ((obj1 (car constraint))
565             (obj2 (cdr constraint)))
566         (let ((info2 (gethash obj2 obj-info)))
567           (if info2
568               (incf (first info2))
569               (setf (gethash obj2 obj-info) (list 1))))
570         (let ((info1 (gethash obj1 obj-info)))
571           (if info1
572               (push obj2 (rest info1))
573               (setf (gethash obj1 obj-info) (list 0 obj2))))))
574     (dolist (obj objects)
575       (let ((info (gethash obj obj-info)))
576         (when (or (not info) (zerop (first info)))
577           (push obj free-objs))))
578     (loop
579      (flet ((next-result (obj)
580               (push obj result)
581               (dolist (successor (rest (gethash obj obj-info)))
582                 (let* ((successor-info (gethash successor obj-info))
583                        (count (1- (first successor-info))))
584                   (setf (first successor-info) count)
585                   (when (zerop count)
586                     (push successor free-objs))))))
587        (cond ((endp free-objs)
588               (dohash (obj info obj-info)
589                 (unless (zerop (first info))
590                   (error "Topological sort failed due to constraint on ~S."
591                          obj)))
592               (return (nreverse result)))
593              ((endp (rest free-objs))
594               (next-result (pop free-objs)))
595              (t
596               (let ((obj (funcall tie-breaker free-objs result)))
597                 (setf free-objs (remove obj free-objs))
598                 (next-result obj))))))))
599
600
601 ;;; standard class precedence list computation
602 (defun std-compute-class-precedence-list (class)
603   (let ((classes nil)
604         (constraints nil))
605     (labels ((note-class (class)
606                (unless (member class classes)
607                  (push class classes)
608                  (let ((superclasses (classoid-direct-superclasses class)))
609                    (do ((prev class)
610                         (rest superclasses (rest rest)))
611                        ((endp rest))
612                      (let ((next (first rest)))
613                        (push (cons prev next) constraints)
614                        (setf prev next)))
615                    (dolist (class superclasses)
616                      (note-class class)))))
617              (std-cpl-tie-breaker (free-classes rev-cpl)
618                (dolist (class rev-cpl (first free-classes))
619                  (let* ((superclasses (classoid-direct-superclasses class))
620                         (intersection (intersection free-classes
621                                                     superclasses)))
622                    (when intersection
623                      (return (first intersection)))))))
624       (note-class class)
625       (topological-sort classes constraints #'std-cpl-tie-breaker))))
626 \f
627 ;;;; object types to represent classes
628
629 ;;; An UNDEFINED-CLASSOID is a cookie we make up to stick in forward
630 ;;; referenced layouts. Users should never see them.
631 (def!struct (undefined-classoid
632              (:include classoid)
633              (:constructor make-undefined-classoid (name))))
634
635 ;;; BUILT-IN-CLASS is used to represent the standard classes that
636 ;;; aren't defined with DEFSTRUCT and other specially implemented
637 ;;; primitive types whose only attribute is their name.
638 ;;;
639 ;;; Some BUILT-IN-CLASSes have a TRANSLATION, which means that they
640 ;;; are effectively DEFTYPE'd to some other type (usually a union of
641 ;;; other classes or a "primitive" type such as NUMBER, ARRAY, etc.)
642 ;;; This translation is done when type specifiers are parsed. Type
643 ;;; system operations (union, subtypep, etc.) should never encounter
644 ;;; translated classes, only their translation.
645 (def!struct (built-in-classoid (:include classoid)
646                                (:constructor make-built-in-classoid))
647   ;; the type we translate to on parsing. If NIL, then this class
648   ;; stands on its own; or it can be set to :INITIALIZING for a period
649   ;; during cold-load.
650   (translation nil :type (or ctype (member nil :initializing))))
651
652 ;;; STRUCTURE-CLASS represents what we need to know about structure
653 ;;; classes. Non-structure "typed" defstructs are a special case, and
654 ;;; don't have a corresponding class.
655 (def!struct (structure-classoid (:include classoid)
656                                 (:constructor make-structure-classoid))
657   ;; If true, a default keyword constructor for this structure.
658   (constructor nil :type (or function null)))
659 \f
660 ;;;; classoid namespace
661
662 ;;; We use an indirection to allow forward referencing of class
663 ;;; definitions with load-time resolution.
664 (def!struct (classoid-cell
665              (:constructor make-classoid-cell (name &optional classoid))
666              (:make-load-form-fun (lambda (c)
667                                     `(find-classoid-cell
668                                       ',(classoid-cell-name c))))
669              #-no-ansi-print-object
670              (:print-object (lambda (s stream)
671                               (print-unreadable-object (s stream :type t)
672                                 (prin1 (classoid-cell-name s) stream)))))
673   ;; Name of class we expect to find.
674   (name nil :type symbol :read-only t)
675   ;; Class or NIL if not yet defined.
676   (classoid nil :type (or classoid null)))
677 (defun find-classoid-cell (name)
678   (or (info :type :classoid name)
679       (setf (info :type :classoid name)
680             (make-classoid-cell name))))
681
682 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
683 (defun find-classoid (name &optional (errorp t) environment)
684   #!+sb-doc
685   "Return the class with the specified NAME. If ERRORP is false, then
686 NIL is returned when no such class exists."
687   (declare (type symbol name) (ignore environment))
688   (let ((res (classoid-cell-classoid (find-classoid-cell name))))
689     (if (or res (not errorp))
690         res
691         (error 'simple-type-error
692                :datum nil
693                :expected-type 'class
694                :format-control "class not yet defined:~%  ~S"
695                :format-arguments (list name)))))
696 (defun (setf find-classoid) (new-value name)
697   #-sb-xc (declare (type (or null classoid) new-value))
698   (cond
699     ((null new-value)
700      (ecase (info :type :kind name)
701        ((nil))
702        (:defined)
703        (:primitive
704         (error "attempt to redefine :PRIMITIVE type: ~S" name))
705        ((:forthcoming-defclass-type :instance)
706         (setf (info :type :kind name) nil
707               (info :type :classoid name) nil
708               (info :type :documentation name) nil
709               (info :type :compiler-layout name) nil))))
710     (t
711      (ecase (info :type :kind name)
712        ((nil))
713        (:forthcoming-defclass-type
714         ;; XXX Currently, nothing needs to be done in this
715         ;; case. Later, when PCL is integrated tighter into SBCL, this
716         ;; might need more work.
717         nil)
718        (:instance
719         ;; KLUDGE: The reason these clauses aren't directly parallel
720         ;; is that we need to use the internal CLASSOID structure
721         ;; ourselves, because we don't have CLASSes to work with until
722         ;; PCL is built.  In the host, CLASSes have an approximately
723         ;; one-to-one correspondence with the target CLASSOIDs (as
724         ;; well as with the target CLASSes, modulo potential
725         ;; differences with respect to conditions).
726         #+sb-xc-host
727         (let ((old (class-of (find-classoid name)))
728               (new (class-of new-value)))
729           (unless (eq old new)
730             (bug "trying to change the metaclass of ~S from ~S to ~S in the ~
731                   cross-compiler."
732                  name (class-name old) (class-name new))))
733         #-sb-xc-host
734         (let ((old (classoid-of (find-classoid name)))
735               (new (classoid-of new-value)))
736           (unless (eq old new)
737             (warn "changing meta-class of ~S from ~S to ~S"
738                   name (classoid-name old) (classoid-name new)))))
739        (:primitive
740         (error "illegal to redefine standard type ~S" name))
741        (:defined
742            (warn "redefining DEFTYPE type to be a class: ~S" name)
743            (setf (info :type :expander name) nil)))
744
745      (remhash name *forward-referenced-layouts*)
746      (%note-type-defined name)
747      ;; we need to handle things like
748      ;;   (setf (find-class 'foo) (find-class 'integer))
749      ;; and
750      ;;   (setf (find-class 'integer) (find-class 'integer))
751      (cond
752        ((built-in-classoid-p new-value)
753         (setf (info :type :kind name) (or (info :type :kind name) :defined))
754         (let ((translation (built-in-classoid-translation new-value)))
755           (when translation
756             (setf (info :type :translator name)
757                   (lambda (c) (declare (ignore c)) translation)))))
758        (t (setf (info :type :kind name) :instance)))
759      (setf (classoid-cell-classoid (find-classoid-cell name)) new-value)
760      (unless (eq (info :type :compiler-layout name)
761                  (classoid-layout new-value))
762        (setf (info :type :compiler-layout name) (classoid-layout new-value)))))
763   new-value)
764 ) ; EVAL-WHEN
765
766 ;;; Called when we are about to define NAME as a class meeting some
767 ;;; predicate (such as a meta-class type test.) The first result is
768 ;;; always of the desired class. The second result is any existing
769 ;;; LAYOUT for this name.
770 (defun insured-find-classoid (name predicate constructor)
771   (declare (type function predicate constructor))
772   (let* ((old (find-classoid name nil))
773          (res (if (and old (funcall predicate old))
774                   old
775                   (funcall constructor :name name)))
776          (found (or (gethash name *forward-referenced-layouts*)
777                     (when old (classoid-layout old)))))
778     (when found
779       (setf (layout-classoid found) res))
780     (values res found)))
781
782 ;;; If the class has a proper name, return the name, otherwise return
783 ;;; the class.
784 (defun classoid-proper-name (class)
785   #-sb-xc (declare (type classoid class))
786   (let ((name (classoid-name class)))
787     (if (and name (eq (find-classoid name nil) class))
788         name
789         class)))
790 \f
791 ;;;; CLASS type operations
792
793 (!define-type-class classoid)
794
795 ;;; We might be passed classoids with invalid layouts; in any pairwise
796 ;;; class comparison, we must ensure that both are valid before
797 ;;; proceeding.
798 (defun ensure-classoid-valid (classoid layout)
799   (aver (eq classoid (layout-classoid layout)))
800   (when (layout-invalid layout)
801     (if (typep classoid 'standard-classoid)
802         (let ((class (classoid-pcl-class classoid)))
803           (cond
804             ((sb!pcl:class-finalized-p class)
805              (sb!pcl::force-cache-flushes class))
806             ((sb!pcl::class-has-a-forward-referenced-superclass-p class)
807              (error "Invalid, unfinalizeable class ~S (classoid ~S)."
808                     class classoid))
809             (t (sb!pcl:finalize-inheritance class))))
810         (error "Don't know how to ensure validity of ~S (not ~
811                 a STANDARD-CLASSOID)." classoid))))
812
813 (defun ensure-both-classoids-valid (class1 class2)
814   (do ((layout1 (classoid-layout class1) (classoid-layout class1))
815        (layout2 (classoid-layout class2) (classoid-layout class2))
816        (i 0 (+ i 1)))
817       ((and (not (layout-invalid layout1)) (not (layout-invalid layout2))))
818     (aver (< i 2))
819     (ensure-classoid-valid class1 layout1)
820     (ensure-classoid-valid class2 layout2)))
821
822 (defun update-object-layout-or-invalid (object layout)
823   (if (typep (classoid-of object) 'standard-classoid)
824       (sb!pcl::check-wrapper-validity object)
825       (sb!c::%layout-invalid-error object layout)))
826
827 ;;; Simple methods for TYPE= and SUBTYPEP should never be called when
828 ;;; the two classes are equal, since there are EQ checks in those
829 ;;; operations.
830 (!define-type-method (classoid :simple-=) (type1 type2)
831   (aver (not (eq type1 type2)))
832   (values nil t))
833
834 (!define-type-method (classoid :simple-subtypep) (class1 class2)
835   (aver (not (eq class1 class2)))
836   (ensure-both-classoids-valid class1 class2)
837   (let ((subclasses (classoid-subclasses class2)))
838     (if (and subclasses (gethash class1 subclasses))
839         (values t t)
840         (values nil t))))
841
842 ;;; When finding the intersection of a sealed class and some other
843 ;;; class (not hierarchically related) the intersection is the union
844 ;;; of the currently shared subclasses.
845 (defun sealed-class-intersection2 (sealed other)
846   (declare (type classoid sealed other))
847   (let ((s-sub (classoid-subclasses sealed))
848         (o-sub (classoid-subclasses other)))
849     (if (and s-sub o-sub)
850         (collect ((res *empty-type* type-union))
851           (dohash (subclass layout s-sub)
852             (declare (ignore layout))
853             (when (gethash subclass o-sub)
854               (res (specifier-type subclass))))
855           (res))
856         *empty-type*)))
857
858 (!define-type-method (classoid :simple-intersection2) (class1 class2)
859   (declare (type classoid class1 class2))
860   (ensure-both-classoids-valid class1 class2)
861   (cond ((eq class1 class2)
862          class1)
863         ;; If one is a subclass of the other, then that is the
864         ;; intersection.
865         ((let ((subclasses (classoid-subclasses class2)))
866            (and subclasses (gethash class1 subclasses)))
867          class1)
868         ((let ((subclasses (classoid-subclasses class1)))
869            (and subclasses (gethash class2 subclasses)))
870          class2)
871         ;; Otherwise, we can't in general be sure that the
872         ;; intersection is empty, since a subclass of both might be
873         ;; defined. But we can eliminate it for some special cases.
874         ((or (structure-classoid-p class1)
875              (structure-classoid-p class2))
876          ;; No subclass of both can be defined.
877          *empty-type*)
878         ((eq (classoid-state class1) :sealed)
879          ;; checking whether a subclass of both can be defined:
880          (sealed-class-intersection2 class1 class2))
881         ((eq (classoid-state class2) :sealed)
882          ;; checking whether a subclass of both can be defined:
883          (sealed-class-intersection2 class2 class1))
884         (t
885          ;; uncertain, since a subclass of both might be defined
886          nil)))
887
888 ;;; KLUDGE: we need this to deal with the special-case INSTANCE and
889 ;;; FUNCALLABLE-INSTANCE types (which used to be CLASSOIDs until CSR
890 ;;; discovered that this was incompatible with the MOP class
891 ;;; hierarchy).  See NAMED :COMPLEX-SUBTYPEP-ARG2
892 (defvar *non-instance-classoid-types*
893   '(symbol system-area-pointer weak-pointer code-component
894     lra fdefn random-class))
895
896 ;;; KLUDGE: we need this because of the need to represent
897 ;;; intersections of two classes, even when empty at a given time, as
898 ;;; uncanonicalized intersections because of the possibility of later
899 ;;; defining a subclass of both classes.  The necessity for changing
900 ;;; the default return value from SUBTYPEP to NIL, T if no alternate
901 ;;; method is present comes about because, unlike the other places we
902 ;;; use INVOKE-COMPLEX-SUBTYPEP-ARG1-METHOD, in HAIRY methods and the
903 ;;; like, classes are in their own hierarchy with no possibility of
904 ;;; mixtures with other type classes.
905 (!define-type-method (classoid :complex-subtypep-arg2) (type1 class2)
906   (if (and (intersection-type-p type1)
907            (> (count-if #'classoid-p (intersection-type-types type1)) 1))
908       (values nil nil)
909       (invoke-complex-subtypep-arg1-method type1 class2 nil t)))
910
911 (!define-type-method (classoid :negate) (type)
912   (make-negation-type :type type))
913
914 (!define-type-method (classoid :unparse) (type)
915   (classoid-proper-name type))
916 \f
917 ;;;; PCL stuff
918
919 ;;; the CLASSOID that we use to represent type information for
920 ;;; STANDARD-CLASS and FUNCALLABLE-STANDARD-CLASS.  The type system
921 ;;; side does not need to distinguish between STANDARD-CLASS and
922 ;;; FUNCALLABLE-STANDARD-CLASS.
923 (def!struct (standard-classoid (:include classoid)
924                                (:constructor make-standard-classoid)))
925 ;;; a metaclass for classes which aren't standardlike but will never
926 ;;; change either.
927 (def!struct (static-classoid (:include classoid)
928                              (:constructor make-static-classoid)))
929 \f
930 ;;;; built-in classes
931
932 ;;; The BUILT-IN-CLASSES list is a data structure which configures the
933 ;;; creation of all the built-in classes. It contains all the info
934 ;;; that we need to maintain the mapping between classes, compile-time
935 ;;; types and run-time type codes. These options are defined:
936 ;;;
937 ;;; :TRANSLATION (default none)
938 ;;;     When this class is "parsed" as a type specifier, it is
939 ;;;     translated into the specified internal type representation,
940 ;;;     rather than being left as a class. This is used for types
941 ;;;     which we want to canonicalize to some other kind of type
942 ;;;     object because in general we want to be able to include more
943 ;;;     information than just the class (e.g. for numeric types.)
944 ;;;
945 ;;; :ENUMERABLE (default NIL)
946 ;;;     The value of the :ENUMERABLE slot in the created class.
947 ;;;     Meaningless in translated classes.
948 ;;;
949 ;;; :STATE (default :SEALED)
950 ;;;     The value of CLASS-STATE which we want on completion,
951 ;;;     indicating whether subclasses can be created at run-time.
952 ;;;
953 ;;; :HIERARCHICAL-P (default T unless any of the inherits are non-hierarchical)
954 ;;;     True if we can assign this class a unique inheritance depth.
955 ;;;
956 ;;; :CODES (default none)
957 ;;;     Run-time type codes which should be translated back to this
958 ;;;     class by CLASS-OF. Unspecified for abstract classes.
959 ;;;
960 ;;; :INHERITS (default this class and T)
961 ;;;     The class-precedence list for this class, with this class and
962 ;;;     T implicit.
963 ;;;
964 ;;; :DIRECT-SUPERCLASSES (default to head of CPL)
965 ;;;     List of the direct superclasses of this class.
966 ;;;
967 ;;; FIXME: This doesn't seem to be needed after cold init (and so can
968 ;;; probably be uninterned at the end of cold init).
969 (defvar *built-in-classes*)
970 (!cold-init-forms
971   (/show0 "setting *BUILT-IN-CLASSES*")
972   (setq
973    *built-in-classes*
974    '((t :state :read-only :translation t)
975      (character :enumerable t
976                 :codes (#.sb!vm:character-widetag)
977                 :translation (character-set)
978                 :prototype-form (code-char 42))
979      (symbol :codes (#.sb!vm:symbol-header-widetag)
980              :prototype-form '#:mu)
981
982      (system-area-pointer :codes (#.sb!vm:sap-widetag)
983                           :prototype-form (sb!sys:int-sap 42))
984      (weak-pointer :codes (#.sb!vm:weak-pointer-widetag)
985       :prototype-form (sb!ext:make-weak-pointer (find-package "CL")))
986      (code-component :codes (#.sb!vm:code-header-widetag))
987      (lra :codes (#.sb!vm:return-pc-header-widetag))
988      (fdefn :codes (#.sb!vm:fdefn-widetag)
989             :prototype-form (sb!kernel:make-fdefn "42"))
990      (random-class) ; used for unknown type codes
991
992      (function
993       :codes (#.sb!vm:closure-header-widetag
994               #.sb!vm:simple-fun-header-widetag)
995       :state :read-only
996       :prototype-form (function (lambda () 42)))
997
998      (number :translation number)
999      (complex
1000       :translation complex
1001       :inherits (number)
1002       :codes (#.sb!vm:complex-widetag)
1003       :prototype-form (complex 42 42))
1004      (complex-single-float
1005       :translation (complex single-float)
1006       :inherits (complex number)
1007       :codes (#.sb!vm:complex-single-float-widetag)
1008       :prototype-form (complex 42f0 42f0))
1009      (complex-double-float
1010       :translation (complex double-float)
1011       :inherits (complex number)
1012       :codes (#.sb!vm:complex-double-float-widetag)
1013       :prototype-form (complex 42d0 42d0))
1014      #!+long-float
1015      (complex-long-float
1016       :translation (complex long-float)
1017       :inherits (complex number)
1018       :codes (#.sb!vm:complex-long-float-widetag)
1019       :prototype-form (complex 42l0 42l0))
1020      (real :translation real :inherits (number))
1021      (float
1022       :translation float
1023       :inherits (real number))
1024      (single-float
1025       :translation single-float
1026       :inherits (float real number)
1027       :codes (#.sb!vm:single-float-widetag)
1028       :prototype-form 42f0)
1029      (double-float
1030       :translation double-float
1031       :inherits (float real number)
1032       :codes (#.sb!vm:double-float-widetag)
1033       :prototype-form 42d0)
1034      #!+long-float
1035      (long-float
1036       :translation long-float
1037       :inherits (float real number)
1038       :codes (#.sb!vm:long-float-widetag)
1039       :prototype-form 42l0)
1040      (rational
1041       :translation rational
1042       :inherits (real number))
1043      (ratio
1044       :translation (and rational (not integer))
1045       :inherits (rational real number)
1046       :codes (#.sb!vm:ratio-widetag)
1047       :prototype-form 1/42)
1048      (integer
1049       :translation integer
1050       :inherits (rational real number))
1051      (fixnum
1052       :translation (integer #.sb!xc:most-negative-fixnum
1053                     #.sb!xc:most-positive-fixnum)
1054       :inherits (integer rational real number)
1055       :codes (#.sb!vm:even-fixnum-lowtag #.sb!vm:odd-fixnum-lowtag)
1056       :prototype-form 42)
1057      (bignum
1058       :translation (and integer (not fixnum))
1059       :inherits (integer rational real number)
1060       :codes (#.sb!vm:bignum-widetag)
1061       :prototype-form (expt 2 #.(* sb!vm:n-word-bits (/ 3 2))))
1062
1063      (array :translation array :codes (#.sb!vm:complex-array-widetag)
1064             :hierarchical-p nil
1065             :prototype-form (make-array nil :adjustable t))
1066      (simple-array
1067       :translation simple-array :codes (#.sb!vm:simple-array-widetag)
1068       :inherits (array)
1069       :prototype-form (make-array nil))
1070      (sequence
1071       :translation (or cons (member nil) vector extended-sequence)
1072       :state :read-only
1073       :depth 2)
1074      (vector
1075       :translation vector :codes (#.sb!vm:complex-vector-widetag)
1076       :direct-superclasses (array sequence)
1077       :inherits (array sequence))
1078      (simple-vector
1079       :translation simple-vector :codes (#.sb!vm:simple-vector-widetag)
1080       :direct-superclasses (vector simple-array)
1081       :inherits (vector simple-array array sequence)
1082       :prototype-form (make-array 0))
1083      (bit-vector
1084       :translation bit-vector :codes (#.sb!vm:complex-bit-vector-widetag)
1085       :inherits (vector array sequence)
1086       :prototype-form (make-array 0 :element-type 'bit :fill-pointer t))
1087      (simple-bit-vector
1088       :translation simple-bit-vector :codes (#.sb!vm:simple-bit-vector-widetag)
1089       :direct-superclasses (bit-vector simple-array)
1090       :inherits (bit-vector vector simple-array
1091                  array sequence)
1092       :prototype-form (make-array 0 :element-type 'bit))
1093      (simple-array-unsigned-byte-2
1094       :translation (simple-array (unsigned-byte 2) (*))
1095       :codes (#.sb!vm:simple-array-unsigned-byte-2-widetag)
1096       :direct-superclasses (vector simple-array)
1097       :inherits (vector simple-array array sequence)
1098       :prototype-form (make-array 0 :element-type '(unsigned-byte 2)))
1099      (simple-array-unsigned-byte-4
1100       :translation (simple-array (unsigned-byte 4) (*))
1101       :codes (#.sb!vm:simple-array-unsigned-byte-4-widetag)
1102       :direct-superclasses (vector simple-array)
1103       :inherits (vector simple-array array sequence)
1104       :prototype-form (make-array 0 :element-type '(unsigned-byte 4)))
1105      (simple-array-unsigned-byte-7
1106       :translation (simple-array (unsigned-byte 7) (*))
1107       :codes (#.sb!vm:simple-array-unsigned-byte-7-widetag)
1108       :direct-superclasses (vector simple-array)
1109       :inherits (vector simple-array array sequence)
1110       :prototype-form (make-array 0 :element-type '(unsigned-byte 7)))
1111      (simple-array-unsigned-byte-8
1112       :translation (simple-array (unsigned-byte 8) (*))
1113       :codes (#.sb!vm:simple-array-unsigned-byte-8-widetag)
1114       :direct-superclasses (vector simple-array)
1115       :inherits (vector simple-array array sequence)
1116       :prototype-form (make-array 0 :element-type '(unsigned-byte 8)))
1117      (simple-array-unsigned-byte-15
1118       :translation (simple-array (unsigned-byte 15) (*))
1119       :codes (#.sb!vm:simple-array-unsigned-byte-15-widetag)
1120       :direct-superclasses (vector simple-array)
1121       :inherits (vector simple-array array sequence)
1122       :prototype-form (make-array 0 :element-type '(unsigned-byte 15)))
1123      (simple-array-unsigned-byte-16
1124       :translation (simple-array (unsigned-byte 16) (*))
1125       :codes (#.sb!vm:simple-array-unsigned-byte-16-widetag)
1126       :direct-superclasses (vector simple-array)
1127       :inherits (vector simple-array array sequence)
1128       :prototype-form (make-array 0 :element-type '(unsigned-byte 16)))
1129      #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
1130      (simple-array-unsigned-byte-29
1131       :translation (simple-array (unsigned-byte 29) (*))
1132       :codes (#.sb!vm:simple-array-unsigned-byte-29-widetag)
1133       :direct-superclasses (vector simple-array)
1134       :inherits (vector simple-array array sequence)
1135       :prototype-form (make-array 0 :element-type '(unsigned-byte 29)))
1136      (simple-array-unsigned-byte-31
1137       :translation (simple-array (unsigned-byte 31) (*))
1138       :codes (#.sb!vm:simple-array-unsigned-byte-31-widetag)
1139       :direct-superclasses (vector simple-array)
1140       :inherits (vector simple-array array sequence)
1141       :prototype-form (make-array 0 :element-type '(unsigned-byte 31)))
1142      (simple-array-unsigned-byte-32
1143       :translation (simple-array (unsigned-byte 32) (*))
1144       :codes (#.sb!vm:simple-array-unsigned-byte-32-widetag)
1145       :direct-superclasses (vector simple-array)
1146       :inherits (vector simple-array array sequence)
1147       :prototype-form (make-array 0 :element-type '(unsigned-byte 32)))
1148      #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
1149      (simple-array-unsigned-byte-60
1150       :translation (simple-array (unsigned-byte 60) (*))
1151       :codes (#.sb!vm:simple-array-unsigned-byte-60-widetag)
1152       :direct-superclasses (vector simple-array)
1153       :inherits (vector simple-array array sequence)
1154       :prototype-form (make-array 0 :element-type '(unsigned-byte 60)))
1155      #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
1156      (simple-array-unsigned-byte-63
1157       :translation (simple-array (unsigned-byte 63) (*))
1158       :codes (#.sb!vm:simple-array-unsigned-byte-63-widetag)
1159       :direct-superclasses (vector simple-array)
1160       :inherits (vector simple-array array sequence)
1161       :prototype-form (make-array 0 :element-type '(unsigned-byte 63)))
1162      #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
1163      (simple-array-unsigned-byte-64
1164       :translation (simple-array (unsigned-byte 64) (*))
1165       :codes (#.sb!vm:simple-array-unsigned-byte-64-widetag)
1166       :direct-superclasses (vector simple-array)
1167       :inherits (vector simple-array array sequence)
1168       :prototype-form (make-array 0 :element-type '(unsigned-byte 64)))
1169      (simple-array-signed-byte-8
1170       :translation (simple-array (signed-byte 8) (*))
1171       :codes (#.sb!vm:simple-array-signed-byte-8-widetag)
1172       :direct-superclasses (vector simple-array)
1173       :inherits (vector simple-array array sequence)
1174       :prototype-form (make-array 0 :element-type '(signed-byte 8)))
1175      (simple-array-signed-byte-16
1176       :translation (simple-array (signed-byte 16) (*))
1177       :codes (#.sb!vm:simple-array-signed-byte-16-widetag)
1178       :direct-superclasses (vector simple-array)
1179       :inherits (vector simple-array array sequence)
1180       :prototype-form (make-array 0 :element-type '(signed-byte 16)))
1181      #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
1182      (simple-array-signed-byte-30
1183       :translation (simple-array (signed-byte 30) (*))
1184       :codes (#.sb!vm:simple-array-signed-byte-30-widetag)
1185       :direct-superclasses (vector simple-array)
1186       :inherits (vector simple-array array sequence)
1187       :prototype-form (make-array 0 :element-type '(signed-byte 30)))
1188      (simple-array-signed-byte-32
1189       :translation (simple-array (signed-byte 32) (*))
1190       :codes (#.sb!vm:simple-array-signed-byte-32-widetag)
1191       :direct-superclasses (vector simple-array)
1192       :inherits (vector simple-array array sequence)
1193       :prototype-form (make-array 0 :element-type '(signed-byte 32)))
1194      #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
1195      (simple-array-signed-byte-61
1196       :translation (simple-array (signed-byte 61) (*))
1197       :codes (#.sb!vm:simple-array-signed-byte-61-widetag)
1198       :direct-superclasses (vector simple-array)
1199       :inherits (vector simple-array array sequence)
1200       :prototype-form (make-array 0 :element-type '(signed-byte 61)))
1201      #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
1202      (simple-array-signed-byte-64
1203       :translation (simple-array (signed-byte 64) (*))
1204       :codes (#.sb!vm:simple-array-signed-byte-64-widetag)
1205       :direct-superclasses (vector simple-array)
1206       :inherits (vector simple-array array sequence)
1207       :prototype-form (make-array 0 :element-type '(signed-byte 64)))
1208      (simple-array-single-float
1209       :translation (simple-array single-float (*))
1210       :codes (#.sb!vm:simple-array-single-float-widetag)
1211       :direct-superclasses (vector simple-array)
1212       :inherits (vector simple-array array sequence)
1213       :prototype-form (make-array 0 :element-type 'single-float))
1214      (simple-array-double-float
1215       :translation (simple-array double-float (*))
1216       :codes (#.sb!vm:simple-array-double-float-widetag)
1217       :direct-superclasses (vector simple-array)
1218       :inherits (vector simple-array array sequence)
1219       :prototype-form (make-array 0 :element-type 'double-float))
1220      #!+long-float
1221      (simple-array-long-float
1222       :translation (simple-array long-float (*))
1223       :codes (#.sb!vm:simple-array-long-float-widetag)
1224       :direct-superclasses (vector simple-array)
1225       :inherits (vector simple-array array sequence)
1226       :prototype-form (make-array 0 :element-type 'long-float))
1227      (simple-array-complex-single-float
1228       :translation (simple-array (complex single-float) (*))
1229       :codes (#.sb!vm:simple-array-complex-single-float-widetag)
1230       :direct-superclasses (vector simple-array)
1231       :inherits (vector simple-array array sequence)
1232       :prototype-form (make-array 0 :element-type '(complex single-float)))
1233      (simple-array-complex-double-float
1234       :translation (simple-array (complex double-float) (*))
1235       :codes (#.sb!vm:simple-array-complex-double-float-widetag)
1236       :direct-superclasses (vector simple-array)
1237       :inherits (vector simple-array array sequence)
1238       :prototype-form (make-array 0 :element-type '(complex double-float)))
1239      #!+long-float
1240      (simple-array-complex-long-float
1241       :translation (simple-array (complex long-float) (*))
1242       :codes (#.sb!vm:simple-array-complex-long-float-widetag)
1243       :direct-superclasses (vector simple-array)
1244       :inherits (vector simple-array array sequence)
1245       :prototype-form (make-array 0 :element-type '(complex long-float)))
1246      (string
1247       :translation string
1248       :direct-superclasses (vector)
1249       :inherits (vector array sequence))
1250      (simple-string
1251       :translation simple-string
1252       :direct-superclasses (string simple-array)
1253       :inherits (string vector simple-array array sequence))
1254      (vector-nil
1255       :translation (vector nil)
1256       :codes (#.sb!vm:complex-vector-nil-widetag)
1257       :direct-superclasses (string)
1258       :inherits (string vector array sequence)
1259       :prototype-form (make-array 0 :element-type 'nil :fill-pointer t))
1260      (simple-array-nil
1261       :translation (simple-array nil (*))
1262       :codes (#.sb!vm:simple-array-nil-widetag)
1263       :direct-superclasses (vector-nil simple-string)
1264       :inherits (vector-nil simple-string string vector simple-array
1265                  array sequence)
1266       :prototype-form (make-array 0 :element-type 'nil))
1267      (base-string
1268       :translation base-string
1269       :codes (#.sb!vm:complex-base-string-widetag)
1270       :direct-superclasses (string)
1271       :inherits (string vector array sequence)
1272       :prototype-form (make-array 0 :element-type 'base-char :fill-pointer t))
1273      (simple-base-string
1274       :translation simple-base-string
1275       :codes (#.sb!vm:simple-base-string-widetag)
1276       :direct-superclasses (base-string simple-string)
1277       :inherits (base-string simple-string string vector simple-array
1278                  array sequence)
1279       :prototype-form (make-array 0 :element-type 'base-char))
1280      #!+sb-unicode
1281      (character-string
1282       :translation (vector character)
1283       :codes (#.sb!vm:complex-character-string-widetag)
1284       :direct-superclasses (string)
1285       :inherits (string vector array sequence)
1286       :prototype-form (make-array 0 :element-type 'character :fill-pointer t))
1287      #!+sb-unicode
1288      (simple-character-string
1289       :translation (simple-array character (*))
1290       :codes (#.sb!vm:simple-character-string-widetag)
1291       :direct-superclasses (character-string simple-string)
1292       :inherits (character-string simple-string string vector simple-array
1293                  array sequence)
1294       :prototype-form (make-array 0 :element-type 'character))
1295      (list
1296       :translation (or cons (member nil))
1297       :inherits (sequence))
1298      (cons
1299       :codes (#.sb!vm:list-pointer-lowtag)
1300       :translation cons
1301       :inherits (list sequence)
1302       :prototype-form (cons nil nil))
1303      (null
1304       :translation (member nil)
1305       :inherits (symbol list sequence)
1306       :direct-superclasses (symbol list)
1307       :prototype-form 'nil)
1308      (stream
1309       :state :read-only
1310       :depth 2)
1311      (file-stream
1312       :state :read-only
1313       :depth 4
1314       :inherits (stream))
1315      (string-stream
1316       :state :read-only
1317       :depth 4
1318       :inherits (stream)))))
1319
1320 ;;; See also src/code/class-init.lisp where we finish setting up the
1321 ;;; translations for built-in types.
1322 (!cold-init-forms
1323   (dolist (x *built-in-classes*)
1324     #-sb-xc-host (/show0 "at head of loop over *BUILT-IN-CLASSES*")
1325     (destructuring-bind
1326         (name &key
1327               (translation nil trans-p)
1328               inherits
1329               codes
1330               enumerable
1331               state
1332               depth
1333               prototype-form
1334               (hierarchical-p t) ; might be modified below
1335               (direct-superclasses (if inherits
1336                                      (list (car inherits))
1337                                      '(t))))
1338         x
1339       (declare (ignore codes state translation prototype-form))
1340       (let ((inherits-list (if (eq name t)
1341                                ()
1342                                (cons t (reverse inherits))))
1343             (classoid (make-built-in-classoid
1344                        :enumerable enumerable
1345                        :name name
1346                        :translation (if trans-p :initializing nil)
1347                        :direct-superclasses
1348                        (if (eq name t)
1349                            nil
1350                            (mapcar #'find-classoid direct-superclasses)))))
1351         (setf (info :type :kind name) #+sb-xc-host :defined #-sb-xc-host :primitive
1352               (classoid-cell-classoid (find-classoid-cell name)) classoid)
1353         (unless trans-p
1354           (setf (info :type :builtin name) classoid))
1355         (let* ((inherits-vector
1356                 (map 'simple-vector
1357                      (lambda (x)
1358                        (let ((super-layout
1359                               (classoid-layout (find-classoid x))))
1360                          (when (minusp (layout-depthoid super-layout))
1361                            (setf hierarchical-p nil))
1362                          super-layout))
1363                      inherits-list))
1364                (depthoid (if hierarchical-p
1365                            (or depth (length inherits-vector))
1366                            -1)))
1367           (register-layout
1368            (find-and-init-or-check-layout name
1369                                           0
1370                                           inherits-vector
1371                                           depthoid
1372                                           0)
1373            :invalidate nil)))))
1374   (/show0 "done with loop over *BUILT-IN-CLASSES*"))
1375
1376 ;;; Define temporary PCL STANDARD-CLASSes. These will be set up
1377 ;;; correctly and the Lisp layout replaced by a PCL wrapper after PCL
1378 ;;; is loaded and the class defined.
1379 (!cold-init-forms
1380   (/show0 "about to define temporary STANDARD-CLASSes")
1381   (dolist (x '(;; Why is STREAM duplicated in this list? Because, when
1382                ;; the inherits-vector of FUNDAMENTAL-STREAM is set up,
1383                ;; a vector containing the elements of the list below,
1384                ;; i.e. '(T STREAM STREAM), is created, and
1385                ;; this is what the function ORDER-LAYOUT-INHERITS
1386                ;; would do, too.
1387                ;;
1388                ;; So, the purpose is to guarantee a valid layout for
1389                ;; the FUNDAMENTAL-STREAM class, matching what
1390                ;; ORDER-LAYOUT-INHERITS would do.
1391                ;; ORDER-LAYOUT-INHERITS would place STREAM at index 2
1392                ;; in the INHERITS(-VECTOR). Index 1 would not be
1393                ;; filled, so STREAM is duplicated there (as
1394                ;; ORDER-LAYOUTS-INHERITS would do). Maybe the
1395                ;; duplicate definition could be removed (removing a
1396                ;; STREAM element), because FUNDAMENTAL-STREAM is
1397                ;; redefined after PCL is set up, anyway. But to play
1398                ;; it safely, we define the class with a valid INHERITS
1399                ;; vector.
1400                (fundamental-stream (t stream stream))))
1401     (/show0 "defining temporary STANDARD-CLASS")
1402     (let* ((name (first x))
1403            (inherits-list (second x))
1404            (classoid (make-standard-classoid :name name))
1405            (classoid-cell (find-classoid-cell name)))
1406       ;; Needed to open-code the MAP, below
1407       (declare (type list inherits-list))
1408       (setf (classoid-cell-classoid classoid-cell) classoid
1409             (info :type :classoid name) classoid-cell
1410             (info :type :kind name) :instance)
1411       (let ((inherits (map 'simple-vector
1412                            (lambda (x)
1413                              (classoid-layout (find-classoid x)))
1414                            inherits-list)))
1415         #-sb-xc-host (/show0 "INHERITS=..") #-sb-xc-host (/hexstr inherits)
1416         (register-layout (find-and-init-or-check-layout name 0 inherits -1 0)
1417                          :invalidate nil))))
1418   (/show0 "done defining temporary STANDARD-CLASSes"))
1419
1420 ;;; Now that we have set up the class heterarchy, seal the sealed
1421 ;;; classes. This must be done after the subclasses have been set up.
1422 (!cold-init-forms
1423   (dolist (x *built-in-classes*)
1424     (destructuring-bind (name &key (state :sealed) &allow-other-keys) x
1425       (setf (classoid-state (find-classoid name)) state))))
1426 \f
1427 ;;;; class definition/redefinition
1428
1429 ;;; This is to be called whenever we are altering a class.
1430 (defun modify-classoid (classoid)
1431   (clear-type-caches)
1432   (when (member (classoid-state classoid) '(:read-only :frozen))
1433     ;; FIXME: This should probably be CERROR.
1434     (warn "making ~(~A~) class ~S writable"
1435           (classoid-state classoid)
1436           (classoid-name classoid))
1437     (setf (classoid-state classoid) nil)))
1438
1439 ;;; Mark LAYOUT as invalid. Setting DEPTHOID -1 helps cause unsafe
1440 ;;; structure type tests to fail. Remove class from all superclasses
1441 ;;; too (might not be registered, so might not be in subclasses of the
1442 ;;; nominal superclasses.)  We set the layout-clos-hash slots to 0 to
1443 ;;; invalidate the wrappers for specialized dispatch functions, which
1444 ;;; use those slots as indexes into tables.
1445 (defun invalidate-layout (layout)
1446   (declare (type layout layout))
1447   (setf (layout-invalid layout) t
1448         (layout-depthoid layout) -1)
1449   (setf (layout-clos-hash layout) 0)
1450   (let ((inherits (layout-inherits layout))
1451         (classoid (layout-classoid layout)))
1452     (modify-classoid classoid)
1453     (dovector (super inherits)
1454       (let ((subs (classoid-subclasses (layout-classoid super))))
1455         (when subs
1456           (remhash classoid subs)))))
1457   (values))
1458 \f
1459 ;;;; cold loading initializations
1460
1461 ;;; FIXME: It would be good to arrange for this to be called when the
1462 ;;; cross-compiler is being built, not just when the target Lisp is
1463 ;;; being cold loaded. Perhaps this could be moved to its own file
1464 ;;; late in the build-order.lisp-expr sequence, and be put in
1465 ;;; !COLD-INIT-FORMS there?
1466 (defun !class-finalize ()
1467   (dohash (name layout *forward-referenced-layouts*)
1468     (let ((class (find-classoid name nil)))
1469       (cond ((not class)
1470              (setf (layout-classoid layout) (make-undefined-classoid name)))
1471             ((eq (classoid-layout class) layout)
1472              (remhash name *forward-referenced-layouts*))
1473             (t
1474              ;; FIXME: ERROR?
1475              (warn "something strange with forward layout for ~S:~%  ~S"
1476                    name
1477                    layout))))))
1478
1479 (!cold-init-forms
1480   #-sb-xc-host (/show0 "about to set *BUILT-IN-CLASS-CODES*")
1481   (setq *built-in-class-codes*
1482         (let* ((initial-element
1483                 (locally
1484                   ;; KLUDGE: There's a FIND-CLASSOID DEFTRANSFORM for
1485                   ;; constant class names which creates fast but
1486                   ;; non-cold-loadable, non-compact code. In this
1487                   ;; context, we'd rather have compact, cold-loadable
1488                   ;; code. -- WHN 19990928
1489                   (declare (notinline find-classoid))
1490                   (classoid-layout (find-classoid 'random-class))))
1491                (res (make-array 256 :initial-element initial-element)))
1492           (dolist (x *built-in-classes* res)
1493             (destructuring-bind (name &key codes &allow-other-keys)
1494                                 x
1495               (let ((layout (classoid-layout (find-classoid name))))
1496                 (dolist (code codes)
1497                   (setf (svref res code) layout)))))))
1498   (setq *null-classoid-layout*
1499         ;; KLUDGE: we use (LET () ...) instead of a LOCALLY here to
1500         ;; work around a bug in the LOCALLY handling in the fopcompiler
1501         ;; (present in 0.9.13-0.9.14.18). -- JES, 2006-07-16
1502         (let ()
1503           (declare (notinline find-classoid))
1504           (classoid-layout (find-classoid 'null))))
1505   #-sb-xc-host (/show0 "done setting *BUILT-IN-CLASS-CODES*"))
1506 \f
1507 (!defun-from-collected-cold-init-forms !classes-cold-init)