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