1.0.15.31: thread-safe FIND-CLASS -- really this time
[sbcl.git] / src / code / defstruct.lisp
1 ;;;; that part of DEFSTRUCT implementation which is needed not just
2 ;;;; in the target Lisp but also in the cross-compilation host
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!KERNEL")
14
15 (/show0 "code/defstruct.lisp 15")
16 \f
17 ;;;; getting LAYOUTs
18
19 ;;; Return the compiler layout for NAME. (The class referred to by
20 ;;; NAME must be a structure-like class.)
21 (defun compiler-layout-or-lose (name)
22   (let ((res (info :type :compiler-layout name)))
23     (cond ((not res)
24            (error "Class is not yet defined or was undefined: ~S" name))
25           ((not (typep (layout-info res) 'defstruct-description))
26            (error "Class is not a structure class: ~S" name))
27           (t res))))
28
29 ;;; Delay looking for compiler-layout until the constructor is being
30 ;;; compiled, since it doesn't exist until after the EVAL-WHEN
31 ;;; (COMPILE) stuff is compiled. (Or, in the oddball case when
32 ;;; DEFSTRUCT is executing in a non-toplevel context, the
33 ;;; compiler-layout still doesn't exist at compilation time, and we
34 ;;; delay still further.)
35 (sb!xc:defmacro %delayed-get-compiler-layout (name)
36   (let ((layout (info :type :compiler-layout name)))
37     (cond (layout
38            ;; ordinary case: When the DEFSTRUCT is at top level,
39            ;; then EVAL-WHEN (COMPILE) stuff will have set up the
40            ;; layout for us to use.
41            (unless (typep (layout-info layout) 'defstruct-description)
42              (error "Class is not a structure class: ~S" name))
43            `,layout)
44           (t
45            ;; KLUDGE: In the case that DEFSTRUCT is not at top-level
46            ;; the layout doesn't exist at compile time. In that case
47            ;; we laboriously look it up at run time. This code will
48            ;; run on every constructor call and will likely be quite
49            ;; slow, so if anyone cares about performance of
50            ;; non-toplevel DEFSTRUCTs, it should be rewritten to be
51            ;; cleverer. -- WHN 2002-10-23
52            (sb!c:compiler-notify
53             "implementation limitation: ~
54              Non-toplevel DEFSTRUCT constructors are slow.")
55            (with-unique-names (layout)
56              `(let ((,layout (info :type :compiler-layout ',name)))
57                 (unless (typep (layout-info ,layout) 'defstruct-description)
58                   (error "Class is not a structure class: ~S" ',name))
59                 ,layout))))))
60
61 ;;; re. %DELAYED-GET-COMPILER-LAYOUT and COMPILE-TIME-FIND-LAYOUT, above..
62 ;;;
63 ;;; FIXME: Perhaps both should be defined with DEFMACRO-MUNDANELY?
64 ;;; FIXME: Do we really need both? If so, their names and implementations
65 ;;; should probably be tweaked to be more parallel.
66 \f
67 ;;;; DEFSTRUCT-DESCRIPTION
68
69 ;;; The DEFSTRUCT-DESCRIPTION structure holds compile-time information
70 ;;; about a structure type.
71 (def!struct (defstruct-description
72              (:conc-name dd-)
73              (:make-load-form-fun just-dump-it-normally)
74              #-sb-xc-host (:pure t)
75              (:constructor make-defstruct-description
76                            (name &aux
77                                  (conc-name (symbolicate name "-"))
78                                  (copier-name (symbolicate "COPY-" name))
79                                  (predicate-name (symbolicate name "-P")))))
80   ;; name of the structure
81   (name (missing-arg) :type symbol :read-only t)
82   ;; documentation on the structure
83   (doc nil :type (or string null))
84   ;; prefix for slot names. If NIL, none.
85   (conc-name nil :type (or symbol null))
86   ;; the name of the primary standard keyword constructor, or NIL if none
87   (default-constructor nil :type (or symbol null))
88   ;; all the explicit :CONSTRUCTOR specs, with name defaulted
89   (constructors () :type list)
90   ;; name of copying function
91   (copier-name nil :type (or symbol null))
92   ;; name of type predicate
93   (predicate-name nil :type (or symbol null))
94   ;; the arguments to the :INCLUDE option, or NIL if no included
95   ;; structure
96   (include nil :type list)
97   ;; properties used to define structure-like classes with an
98   ;; arbitrary superclass and that may not have STRUCTURE-CLASS as the
99   ;; metaclass. Syntax is:
100   ;;    (superclass-name metaclass-name metaclass-constructor)
101   (alternate-metaclass nil :type list)
102   ;; a list of DEFSTRUCT-SLOT-DESCRIPTION objects for all slots
103   ;; (including included ones)
104   (slots () :type list)
105   ;; a list of (NAME . INDEX) pairs for accessors of included structures
106   (inherited-accessor-alist () :type list)
107   ;; number of elements we've allocated (See also RAW-LENGTH, which is not
108   ;; included in LENGTH.)
109   (length 0 :type index)
110   ;; General kind of implementation.
111   (type 'structure :type (member structure vector list
112                                  funcallable-structure))
113
114   ;; The next three slots are for :TYPE'd structures (which aren't
115   ;; classes, DD-CLASS-P = NIL)
116   ;;
117   ;; vector element type
118   (element-type t)
119   ;; T if :NAMED was explicitly specified, NIL otherwise
120   (named nil :type boolean)
121   ;; any INITIAL-OFFSET option on this direct type
122   (offset nil :type (or index null))
123
124   ;; the argument to the PRINT-FUNCTION option, or NIL if a
125   ;; PRINT-FUNCTION option was given with no argument, or 0 if no
126   ;; PRINT-FUNCTION option was given
127   (print-function 0 :type (or cons symbol (member 0)))
128   ;; the argument to the PRINT-OBJECT option, or NIL if a PRINT-OBJECT
129   ;; option was given with no argument, or 0 if no PRINT-OBJECT option
130   ;; was given
131   (print-object 0 :type (or cons symbol (member 0)))
132   ;; The number of untagged slots at the end.
133   (raw-length 0 :type index)
134   ;; the value of the :PURE option, or :UNSPECIFIED. This is only
135   ;; meaningful if DD-CLASS-P = T.
136   (pure :unspecified :type (member t nil :substructure :unspecified)))
137 (def!method print-object ((x defstruct-description) stream)
138   (print-unreadable-object (x stream :type t)
139     (prin1 (dd-name x) stream)))
140
141 ;;; Does DD describe a structure with a class?
142 (defun dd-class-p (dd)
143   (member (dd-type dd)
144           '(structure funcallable-structure)))
145
146 ;;; a type name which can be used when declaring things which operate
147 ;;; on structure instances
148 (defun dd-declarable-type (dd)
149   (if (dd-class-p dd)
150       ;; Native classes are known to the type system, and we can
151       ;; declare them as types.
152       (dd-name dd)
153       ;; Structures layered on :TYPE LIST or :TYPE VECTOR aren't part
154       ;; of the type system, so all we can declare is the underlying
155       ;; LIST or VECTOR type.
156       (dd-type dd)))
157
158 (defun dd-layout-or-lose (dd)
159   (compiler-layout-or-lose (dd-name dd)))
160 \f
161 ;;;; DEFSTRUCT-SLOT-DESCRIPTION
162
163 ;;; A DEFSTRUCT-SLOT-DESCRIPTION holds compile-time information about
164 ;;; a structure slot.
165 (def!struct (defstruct-slot-description
166              (:make-load-form-fun just-dump-it-normally)
167              (:conc-name dsd-)
168              (:copier nil)
169              #-sb-xc-host (:pure t))
170   ;; name of slot
171   name
172   ;; its position in the implementation sequence
173   (index (missing-arg) :type fixnum)
174   ;; the name of the accessor function
175   ;;
176   ;; (CMU CL had extra complexity here ("..or NIL if this accessor has
177   ;; the same name as an inherited accessor (which we don't want to
178   ;; shadow)") but that behavior doesn't seem to be specified by (or
179   ;; even particularly consistent with) ANSI, so it's gone in SBCL.)
180   (accessor-name nil)
181   default                       ; default value expression
182   (type t)                      ; declared type specifier
183   (safe-p t :type boolean)      ; whether the slot is known to be
184                                 ; always of the specified type
185   ;; If this object does not describe a raw slot, this value is T.
186   ;;
187   ;; If this object describes a raw slot, this value is the type of the
188   ;; value that the raw slot holds.
189   (raw-type t :type (member t single-float double-float
190                             #!+long-float long-float
191                             complex-single-float complex-double-float
192                             #!+long-float complex-long-float
193                             sb!vm:word))
194   (read-only nil :type (member t nil)))
195 (def!method print-object ((x defstruct-slot-description) stream)
196   (print-unreadable-object (x stream :type t)
197     (prin1 (dsd-name x) stream)))
198 \f
199 ;;;; typed (non-class) structures
200
201 ;;; Return a type specifier we can use for testing :TYPE'd structures.
202 (defun dd-lisp-type (defstruct)
203   (ecase (dd-type defstruct)
204     (list 'list)
205     (vector `(simple-array ,(dd-element-type defstruct) (*)))))
206 \f
207 ;;;; shared machinery for inline and out-of-line slot accessor functions
208
209 ;;; Classic comment preserved for entertainment value:
210 ;;;
211 ;;; "A lie can travel halfway round the world while the truth is
212 ;;; putting on its shoes." -- Mark Twain
213
214 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
215
216   ;; information about how a slot of a given DSD-RAW-TYPE is to be accessed
217   (defstruct raw-slot-data
218     ;; the raw slot type, or T for a non-raw slot
219     ;;
220     ;; (Non-raw slots are in the ordinary place you'd expect, directly
221     ;; indexed off the instance pointer.  Raw slots are indexed from the end
222     ;; of the instance and skipped by GC.)
223     (raw-type (missing-arg) :type (or symbol cons) :read-only t)
224     ;; What operator is used to access a slot of this type?
225     (accessor-name (missing-arg) :type symbol :read-only t)
226     ;; How many words are each value of this type?
227     (n-words (missing-arg) :type (and index (integer 1)) :read-only t)
228     ;; Necessary alignment in units of words.  Note that instances
229     ;; themselves are aligned by exactly two words, so specifying more
230     ;; than two words here would not work.
231     (alignment 1 :type (integer 1 2) :read-only t))
232
233   (defvar *raw-slot-data-list*
234     #!+hppa
235     nil
236     #!-hppa
237     (let ((double-float-alignment
238            ;; white list of architectures that can load unaligned doubles:
239            #!+(or x86 x86-64 ppc) 1
240            ;; at least sparc, mips and alpha can't:
241            #!-(or x86 x86-64 ppc) 2))
242       (list
243        (make-raw-slot-data :raw-type 'sb!vm:word
244                            :accessor-name '%raw-instance-ref/word
245                            :n-words 1)
246        (make-raw-slot-data :raw-type 'single-float
247                            :accessor-name '%raw-instance-ref/single
248                            ;; KLUDGE: On 64 bit architectures, we
249                            ;; could pack two SINGLE-FLOATs into the
250                            ;; same word if raw slots were indexed
251                            ;; using bytes instead of words.  However,
252                            ;; I don't personally find optimizing
253                            ;; SINGLE-FLOAT memory usage worthwile
254                            ;; enough.  And the other datatype that
255                            ;; would really benefit is (UNSIGNED-BYTE
256                            ;; 32), but that is a subtype of FIXNUM, so
257                            ;; we store it unraw anyway.  :-( -- DFL
258                            :n-words 1)
259        (make-raw-slot-data :raw-type 'double-float
260                            :accessor-name '%raw-instance-ref/double
261                            :alignment double-float-alignment
262                            :n-words (/ 8 sb!vm:n-word-bytes))
263        (make-raw-slot-data :raw-type 'complex-single-float
264                            :accessor-name '%raw-instance-ref/complex-single
265                            :n-words (/ 8 sb!vm:n-word-bytes))
266        (make-raw-slot-data :raw-type 'complex-double-float
267                            :accessor-name '%raw-instance-ref/complex-double
268                            :alignment double-float-alignment
269                            :n-words (/ 16 sb!vm:n-word-bytes))
270        #!+long-float
271        (make-raw-slot-data :raw-type long-float
272                            :accessor-name '%raw-instance-ref/long
273                            :n-words #!+x86 3 #!+sparc 4)
274        #!+long-float
275        (make-raw-slot-data :raw-type complex-long-float
276                            :accessor-name '%raw-instance-ref/complex-long
277                            :n-words #!+x86 6 #!+sparc 8)))))
278 \f
279 ;;;; the legendary DEFSTRUCT macro itself (both CL:DEFSTRUCT and its
280 ;;;; close personal friend SB!XC:DEFSTRUCT)
281
282 ;;; Return a list of forms to install PRINT and MAKE-LOAD-FORM funs,
283 ;;; mentioning them in the expansion so that they can be compiled.
284 (defun class-method-definitions (defstruct)
285   (let ((name (dd-name defstruct)))
286     `((locally
287         ;; KLUDGE: There's a FIND-CLASS DEFTRANSFORM for constant
288         ;; class names which creates fast but non-cold-loadable,
289         ;; non-compact code. In this context, we'd rather have
290         ;; compact, cold-loadable code. -- WHN 19990928
291         (declare (notinline find-classoid))
292         ,@(let ((pf (dd-print-function defstruct))
293                 (po (dd-print-object defstruct))
294                 (x (gensym))
295                 (s (gensym)))
296             ;; Giving empty :PRINT-OBJECT or :PRINT-FUNCTION options
297             ;; leaves PO or PF equal to NIL. The user-level effect is
298             ;; to generate a PRINT-OBJECT method specialized for the type,
299             ;; implementing the default #S structure-printing behavior.
300             (when (or (eq pf nil) (eq po nil))
301               (setf pf '(default-structure-print)
302                     po 0))
303             (flet (;; Given an arg from a :PRINT-OBJECT or :PRINT-FUNCTION
304                    ;; option, return the value to pass as an arg to FUNCTION.
305                    (farg (oarg)
306                      (destructuring-bind (fun-name) oarg
307                        fun-name)))
308               (cond ((not (eql pf 0))
309                      `((def!method print-object ((,x ,name) ,s)
310                          (funcall #',(farg pf)
311                                   ,x
312                                   ,s
313                                   *current-level-in-print*))))
314                     ((not (eql po 0))
315                      `((def!method print-object ((,x ,name) ,s)
316                          (funcall #',(farg po) ,x ,s))))
317                     (t nil))))
318         ,@(let ((pure (dd-pure defstruct)))
319             (cond ((eq pure t)
320                    `((setf (layout-pure (classoid-layout
321                                          (find-classoid ',name)))
322                            t)))
323                   ((eq pure :substructure)
324                    `((setf (layout-pure (classoid-layout
325                                          (find-classoid ',name)))
326                            0)))))
327         ,@(let ((def-con (dd-default-constructor defstruct)))
328             (when (and def-con (not (dd-alternate-metaclass defstruct)))
329               `((setf (structure-classoid-constructor (find-classoid ',name))
330                       #',def-con))))))))
331
332 ;;; shared logic for host macroexpansion for SB!XC:DEFSTRUCT and
333 ;;; cross-compiler macroexpansion for CL:DEFSTRUCT
334 (defmacro !expander-for-defstruct (name-and-options
335                                    slot-descriptions
336                                    expanding-into-code-for-xc-host-p)
337   `(let ((name-and-options ,name-and-options)
338          (slot-descriptions ,slot-descriptions)
339          (expanding-into-code-for-xc-host-p
340           ,expanding-into-code-for-xc-host-p))
341      (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
342                  name-and-options
343                  slot-descriptions))
344             (name (dd-name dd)))
345        (if (dd-class-p dd)
346            (let ((inherits (inherits-for-structure dd)))
347              `(progn
348                 ;; Note we intentionally enforce package locks and
349                 ;; call %DEFSTRUCT first, and especially before
350                 ;; %COMPILER-DEFSTRUCT. %DEFSTRUCT has the tests (and
351                 ;; resulting CERROR) for collisions with LAYOUTs which
352                 ;; already exist in the runtime. If there are any
353                 ;; collisions, we want the user's response to CERROR
354                 ;; to control what happens. Especially, if the user
355                 ;; responds to the collision with ABORT, we don't want
356                 ;; %COMPILER-DEFSTRUCT to modify the definition of the
357                 ;; class.
358                 (with-single-package-locked-error
359                     (:symbol ',name "defining ~A as a structure"))
360                 (%defstruct ',dd ',inherits (sb!c:source-location))
361                 (eval-when (:compile-toplevel :load-toplevel :execute)
362                   (%compiler-defstruct ',dd ',inherits))
363                 ,@(unless expanding-into-code-for-xc-host-p
364                     (append ;; FIXME: We've inherited from CMU CL nonparallel
365                             ;; code for creating copiers for typed and untyped
366                             ;; structures. This should be fixed.
367                             ;(copier-definition dd)
368                             (constructor-definitions dd)
369                             (class-method-definitions dd)))
370                 ',name))
371            `(progn
372               (with-single-package-locked-error
373                   (:symbol ',name "defining ~A as a structure"))
374               (eval-when (:compile-toplevel :load-toplevel :execute)
375                 (setf (info :typed-structure :info ',name) ',dd))
376               (eval-when (:load-toplevel :execute)
377                 (setf (info :source-location :typed-structure ',name)
378                       (sb!c:source-location)))
379               ,@(unless expanding-into-code-for-xc-host-p
380                   (append (typed-accessor-definitions dd)
381                           (typed-predicate-definitions dd)
382                           (typed-copier-definitions dd)
383                           (constructor-definitions dd)
384                           (when (dd-doc dd)
385                             `((setf (fdocumentation ',(dd-name dd) 'structure)
386                                ',(dd-doc dd))))))
387               ',name)))))
388
389 (sb!xc:defmacro defstruct (name-and-options &rest slot-descriptions)
390   #!+sb-doc
391   "DEFSTRUCT {Name | (Name Option*)} {Slot | (Slot [Default] {Key Value}*)}
392    Define the structure type Name. Instances are created by MAKE-<name>,
393    which takes &KEY arguments allowing initial slot values to the specified.
394    A SETF'able function <name>-<slot> is defined for each slot to read and
395    write slot values. <name>-p is a type predicate.
396
397    Popular DEFSTRUCT options (see manual for others):
398
399    (:CONSTRUCTOR Name)
400    (:PREDICATE Name)
401        Specify the name for the constructor or predicate.
402
403    (:CONSTRUCTOR Name Lambda-List)
404        Specify the name and arguments for a BOA constructor
405        (which is more efficient when keyword syntax isn't necessary.)
406
407    (:INCLUDE Supertype Slot-Spec*)
408        Make this type a subtype of the structure type Supertype. The optional
409        Slot-Specs override inherited slot options.
410
411    Slot options:
412
413    :TYPE Type-Spec
414        Asserts that the value of this slot is always of the specified type.
415
416    :READ-ONLY {T | NIL}
417        If true, no setter function is defined for this slot."
418     (!expander-for-defstruct name-and-options slot-descriptions nil))
419 #+sb-xc-host
420 (defmacro sb!xc:defstruct (name-and-options &rest slot-descriptions)
421   #!+sb-doc
422   "Cause information about a target structure to be built into the
423   cross-compiler."
424   (!expander-for-defstruct name-and-options slot-descriptions t))
425 \f
426 ;;;; functions to generate code for various parts of DEFSTRUCT definitions
427
428 ;;; First, a helper to determine whether a name names an inherited
429 ;;; accessor.
430 (defun accessor-inherited-data (name defstruct)
431   (assoc name (dd-inherited-accessor-alist defstruct) :test #'eq))
432
433 ;;; Return a list of forms which create a predicate function for a
434 ;;; typed DEFSTRUCT.
435 (defun typed-predicate-definitions (defstruct)
436   (let ((name (dd-name defstruct))
437         (predicate-name (dd-predicate-name defstruct))
438         (argname (gensym)))
439     (when (and predicate-name (dd-named defstruct))
440       (let ((ltype (dd-lisp-type defstruct))
441             (name-index (cdr (car (last (find-name-indices defstruct))))))
442         `((defun ,predicate-name (,argname)
443             (and (typep ,argname ',ltype)
444                  ,(cond
445                    ((subtypep ltype 'list)
446                      `(do ((head (the ,ltype ,argname) (cdr head))
447                            (i 0 (1+ i)))
448                           ((or (not (consp head)) (= i ,name-index))
449                            (and (consp head) (eq ',name (car head))))))
450                    ((subtypep ltype 'vector)
451                     `(and (= (length (the ,ltype ,argname))
452                            ,(dd-length defstruct))
453                           (eq ',name (aref (the ,ltype ,argname) ,name-index))))
454                    (t (bug "Uncatered-for lisp type in typed DEFSTRUCT: ~S."
455                            ltype))))))))))
456
457 ;;; Return a list of forms to create a copier function of a typed DEFSTRUCT.
458 (defun typed-copier-definitions (defstruct)
459   (when (dd-copier-name defstruct)
460     `((setf (fdefinition ',(dd-copier-name defstruct)) #'copy-seq)
461       (declaim (ftype function ,(dd-copier-name defstruct))))))
462
463 ;;; Return a list of function definitions for accessing and setting
464 ;;; the slots of a typed DEFSTRUCT. The functions are proclaimed to be
465 ;;; inline, and the types of their arguments and results are declared
466 ;;; as well. We count on the compiler to do clever things with ELT.
467 (defun typed-accessor-definitions (defstruct)
468   (collect ((stuff))
469     (let ((ltype (dd-lisp-type defstruct)))
470       (dolist (slot (dd-slots defstruct))
471         (let ((name (dsd-accessor-name slot))
472               (index (dsd-index slot))
473               (slot-type `(and ,(dsd-type slot)
474                                ,(dd-element-type defstruct))))
475           (let ((inherited (accessor-inherited-data name defstruct)))
476             (cond
477               ((not inherited)
478                (stuff `(declaim (inline ,name ,@(unless (dsd-read-only slot)
479                                                         `((setf ,name))))))
480                ;; FIXME: The arguments in the next two DEFUNs should
481                ;; be gensyms. (Otherwise e.g. if NEW-VALUE happened to
482                ;; be the name of a special variable, things could get
483                ;; weird.)
484                (stuff `(defun ,name (structure)
485                         (declare (type ,ltype structure))
486                         (the ,slot-type (elt structure ,index))))
487                (unless (dsd-read-only slot)
488                  (stuff
489                   `(defun (setf ,name) (new-value structure)
490                     (declare (type ,ltype structure) (type ,slot-type new-value))
491                     (setf (elt structure ,index) new-value)))))
492               ((not (= (cdr inherited) index))
493                (style-warn "~@<Non-overwritten accessor ~S does not access ~
494                             slot with name ~S (accessing an inherited slot ~
495                             instead).~:@>" name (dsd-name slot))))))))
496     (stuff)))
497 \f
498 ;;;; parsing
499
500 (defun require-no-print-options-so-far (defstruct)
501   (unless (and (eql (dd-print-function defstruct) 0)
502                (eql (dd-print-object defstruct) 0))
503     (error "No more than one of the following options may be specified:
504   :PRINT-FUNCTION, :PRINT-OBJECT, :TYPE")))
505
506 ;;; Parse a single DEFSTRUCT option and store the results in DD.
507 (defun parse-1-dd-option (option dd)
508   (let ((args (rest option))
509         (name (dd-name dd)))
510     (case (first option)
511       (:conc-name
512        (destructuring-bind (&optional conc-name) args
513          (setf (dd-conc-name dd)
514                (if (symbolp conc-name)
515                    conc-name
516                    (make-symbol (string conc-name))))))
517       (:constructor
518        (destructuring-bind (&optional (cname (symbolicate "MAKE-" name))
519                                       &rest stuff)
520            args
521          (push (cons cname stuff) (dd-constructors dd))))
522       (:copier
523        (destructuring-bind (&optional (copier (symbolicate "COPY-" name)))
524            args
525          (setf (dd-copier-name dd) copier)))
526       (:predicate
527        (destructuring-bind (&optional (predicate-name (symbolicate name "-P")))
528            args
529          (setf (dd-predicate-name dd) predicate-name)))
530       (:include
531        (when (dd-include dd)
532          (error "more than one :INCLUDE option"))
533        (setf (dd-include dd) args))
534       (:print-function
535        (require-no-print-options-so-far dd)
536        (setf (dd-print-function dd)
537              (the (or symbol cons) args)))
538       (:print-object
539        (require-no-print-options-so-far dd)
540        (setf (dd-print-object dd)
541              (the (or symbol cons) args)))
542       (:type
543        (destructuring-bind (type) args
544          (cond ((member type '(list vector))
545                 (setf (dd-element-type dd) t)
546                 (setf (dd-type dd) type))
547                ((and (consp type) (eq (first type) 'vector))
548                 (destructuring-bind (vector vtype) type
549                   (declare (ignore vector))
550                   (setf (dd-element-type dd) vtype)
551                   (setf (dd-type dd) 'vector)))
552                (t
553                 (error "~S is a bad :TYPE for DEFSTRUCT." type)))))
554       (:named
555        (error "The DEFSTRUCT option :NAMED takes no arguments."))
556       (:initial-offset
557        (destructuring-bind (offset) args
558          (setf (dd-offset dd) offset)))
559       (:pure
560        (destructuring-bind (fun) args
561          (setf (dd-pure dd) fun)))
562       (t (error "unknown DEFSTRUCT option:~%  ~S" option)))))
563
564 ;;; Given name and options, return a DD holding that info.
565 (defun parse-defstruct-name-and-options (name-and-options)
566   (destructuring-bind (name &rest options) name-and-options
567     (aver name) ; A null name doesn't seem to make sense here.
568     (let ((dd (make-defstruct-description name)))
569       (dolist (option options)
570         (cond ((eq option :named)
571                (setf (dd-named dd) t))
572               ((consp option)
573                (parse-1-dd-option option dd))
574               ((member option '(:conc-name :constructor :copier :predicate))
575                (parse-1-dd-option (list option) dd))
576               (t
577                (error "unrecognized DEFSTRUCT option: ~S" option))))
578
579       (case (dd-type dd)
580         (structure
581          (when (dd-offset dd)
582            (error ":OFFSET can't be specified unless :TYPE is specified."))
583          (unless (dd-include dd)
584            ;; FIXME: It'd be cleaner to treat no-:INCLUDE as defaulting
585            ;; to :INCLUDE STRUCTURE-OBJECT, and then let the general-case
586            ;; (INCF (DD-LENGTH DD) (DD-LENGTH included-DD)) logic take
587            ;; care of this. (Except that the :TYPE VECTOR and :TYPE
588            ;; LIST cases, with their :NAMED and un-:NAMED flavors,
589            ;; make that messy, alas.)
590            (incf (dd-length dd))))
591         (t
592          (require-no-print-options-so-far dd)
593          (when (dd-named dd)
594            (incf (dd-length dd)))
595          (let ((offset (dd-offset dd)))
596            (when offset (incf (dd-length dd) offset)))))
597
598       (when (dd-include dd)
599         (frob-dd-inclusion-stuff dd))
600
601       dd)))
602
603 ;;; Given name and options and slot descriptions (and possibly doc
604 ;;; string at the head of slot descriptions) return a DD holding that
605 ;;; info.
606 (defun parse-defstruct-name-and-options-and-slot-descriptions
607     (name-and-options slot-descriptions)
608   (let ((result (parse-defstruct-name-and-options (if (atom name-and-options)
609                                                       (list name-and-options)
610                                                       name-and-options))))
611     (when (stringp (car slot-descriptions))
612       (setf (dd-doc result) (pop slot-descriptions)))
613     (dolist (slot-description slot-descriptions)
614       (allocate-1-slot result (parse-1-dsd result slot-description)))
615     result))
616 \f
617 ;;;; stuff to parse slot descriptions
618
619 ;;; Parse a slot description for DEFSTRUCT, add it to the description
620 ;;; and return it. If supplied, SLOT is a pre-initialized DSD
621 ;;; that we modify to get the new slot. This is supplied when handling
622 ;;; included slots.
623 (defun parse-1-dsd (defstruct spec &optional
624                     (slot (make-defstruct-slot-description :name ""
625                                                            :index 0
626                                                            :type t)))
627   (multiple-value-bind (name default default-p type type-p read-only ro-p)
628       (typecase spec
629         (symbol
630          (when (keywordp spec)
631            (style-warn "Keyword slot name indicates probable syntax ~
632                         error in DEFSTRUCT: ~S."
633                        spec))
634          spec)
635         (cons
636          (destructuring-bind
637                (name
638                 &optional (default nil default-p)
639                 &key (type nil type-p) (read-only nil ro-p))
640              spec
641            (values name
642                    default default-p
643                    (uncross type) type-p
644                    read-only ro-p)))
645         (t (error 'simple-program-error
646                   :format-control "in DEFSTRUCT, ~S is not a legal slot ~
647                                    description."
648                   :format-arguments (list spec))))
649
650     (when (find name (dd-slots defstruct)
651                 :test #'string=
652                 :key (lambda (x) (symbol-name (dsd-name x))))
653       (error 'simple-program-error
654              :format-control "duplicate slot name ~S"
655              :format-arguments (list name)))
656     (setf (dsd-name slot) name)
657     (setf (dd-slots defstruct) (nconc (dd-slots defstruct) (list slot)))
658
659     (let ((accessor-name (if (dd-conc-name defstruct)
660                              (symbolicate (dd-conc-name defstruct) name)
661                              name))
662           (predicate-name (dd-predicate-name defstruct)))
663       (setf (dsd-accessor-name slot) accessor-name)
664       (when (eql accessor-name predicate-name)
665         ;; Some adventurous soul has named a slot so that its accessor
666         ;; collides with the structure type predicate. ANSI doesn't
667         ;; specify what to do in this case. As of 2001-09-04, Martin
668         ;; Atzmueller reports that CLISP and Lispworks both give
669         ;; priority to the slot accessor, so that the predicate is
670         ;; overwritten. We might as well do the same (as well as
671         ;; signalling a warning).
672         (style-warn
673          "~@<The structure accessor name ~S is the same as the name of the ~
674           structure type predicate. ANSI doesn't specify what to do in ~
675           this case. We'll overwrite the type predicate with the slot ~
676           accessor, but you can't rely on this behavior, so it'd be wise to ~
677           remove the ambiguity in your code.~@:>"
678          accessor-name)
679         (setf (dd-predicate-name defstruct) nil))
680       ;; FIXME: It would be good to check for name collisions here, but
681       ;; the easy check,
682       ;;x#-sb-xc-host
683       ;;x(when (and (fboundp accessor-name)
684       ;;x           (not (accessor-inherited-data accessor-name defstruct)))
685       ;;x  (style-warn "redefining ~S in DEFSTRUCT" accessor-name)))
686       ;; which was done until sbcl-0.8.11.18 or so, is wrong: it causes
687       ;; a warning at MACROEXPAND time, when instead the warning should
688       ;; occur not just because the code was constructed, but because it
689       ;; is actually compiled or loaded.
690       )
691
692     (when default-p
693       (setf (dsd-default slot) default))
694     (when type-p
695       (setf (dsd-type slot)
696             (if (eq (dsd-type slot) t)
697                 type
698                 `(and ,(dsd-type slot) ,type))))
699     (when ro-p
700       (if read-only
701           (setf (dsd-read-only slot) t)
702           (when (dsd-read-only slot)
703             (error "~@<The slot ~S is :READ-ONLY in superclass, and so must ~
704                        be :READ-ONLY in subclass.~:@>"
705                    (dsd-name slot)))))
706     slot))
707
708 ;;; When a value of type TYPE is stored in a structure, should it be
709 ;;; stored in a raw slot?  Return the matching RAW-SLOT-DATA structure
710 ;; if TYPE should be stored in a raw slot, or NIL if not.
711 (defun structure-raw-slot-data (type)
712   (multiple-value-bind (fixnum? fixnum-certain?)
713       (sb!xc:subtypep type 'fixnum)
714     ;; (The extra test for FIXNUM-CERTAIN? here is intended for
715     ;; bootstrapping the system. In particular, in sbcl-0.6.2, we set up
716     ;; LAYOUT before FIXNUM is defined, and so could bogusly end up
717     ;; putting INDEX-typed values into raw slots if we didn't test
718     ;; FIXNUM-CERTAIN?.)
719     (if (or fixnum? (not fixnum-certain?))
720         nil
721         (dolist (data *raw-slot-data-list*)
722           (when (sb!xc:subtypep type (raw-slot-data-raw-type data))
723             (return data))))))
724
725 ;;; Allocate storage for a DSD in DD. This is where we decide whether
726 ;;; a slot is raw or not. Raw objects are aligned on the unit of their size.
727 (defun allocate-1-slot (dd dsd)
728   (let ((rsd
729          (if (eq (dd-type dd) 'structure)
730              (structure-raw-slot-data (dsd-type dsd))
731              nil)))
732     (cond
733       ((null rsd)
734         (setf (dsd-index dsd) (dd-length dd))
735         (incf (dd-length dd)))
736       (t
737         (let* ((words (raw-slot-data-n-words rsd))
738                (alignment (raw-slot-data-alignment rsd))
739                (off (rem (dd-raw-length dd) alignment)))
740           (unless (zerop off)
741             (incf (dd-raw-length dd) (- alignment off)))
742           (setf (dsd-raw-type dsd) (raw-slot-data-raw-type rsd))
743           (setf (dsd-index dsd) (dd-raw-length dd))
744           (incf (dd-raw-length dd) words)))))
745   (values))
746
747 (defun typed-structure-info-or-lose (name)
748   (or (info :typed-structure :info name)
749       (error ":TYPE'd DEFSTRUCT ~S not found for inclusion." name)))
750
751 ;;; Process any included slots pretty much like they were specified.
752 ;;; Also inherit various other attributes.
753 (defun frob-dd-inclusion-stuff (dd)
754   (destructuring-bind (included-name &rest modified-slots) (dd-include dd)
755     (let* ((type (dd-type dd))
756            (included-structure
757             (if (dd-class-p dd)
758                 (layout-info (compiler-layout-or-lose included-name))
759                 (typed-structure-info-or-lose included-name))))
760
761       ;; checks on legality
762       (unless (and (eq type (dd-type included-structure))
763                    (type= (specifier-type (dd-element-type included-structure))
764                           (specifier-type (dd-element-type dd))))
765         (error ":TYPE option mismatch between structures ~S and ~S"
766                (dd-name dd) included-name))
767       (let ((included-classoid (find-classoid included-name nil)))
768         (when included-classoid
769           ;; It's not particularly well-defined to :INCLUDE any of the
770           ;; CMU CL INSTANCE weirdosities like CONDITION or
771           ;; GENERIC-FUNCTION, and it's certainly not ANSI-compliant.
772           (let* ((included-layout (classoid-layout included-classoid))
773                  (included-dd (layout-info included-layout)))
774             (when (and (dd-alternate-metaclass included-dd)
775                        ;; As of sbcl-0.pre7.73, anyway, STRUCTURE-OBJECT
776                        ;; is represented with an ALTERNATE-METACLASS. But
777                        ;; it's specifically OK to :INCLUDE (and PCL does)
778                        ;; so in this one case, it's OK to include
779                        ;; something with :ALTERNATE-METACLASS after all.
780                        (not (eql included-name 'structure-object)))
781               (error "can't :INCLUDE class ~S (has alternate metaclass)"
782                      included-name)))))
783
784       (incf (dd-length dd) (dd-length included-structure))
785       (when (dd-class-p dd)
786         (let ((mc (rest (dd-alternate-metaclass included-structure))))
787           (when (and mc (not (dd-alternate-metaclass dd)))
788             (setf (dd-alternate-metaclass dd)
789                   (cons included-name mc))))
790         (when (eq (dd-pure dd) :unspecified)
791           (setf (dd-pure dd) (dd-pure included-structure)))
792         (setf (dd-raw-length dd) (dd-raw-length included-structure)))
793
794       (setf (dd-inherited-accessor-alist dd)
795             (dd-inherited-accessor-alist included-structure))
796       (dolist (included-slot (dd-slots included-structure))
797         (let* ((included-name (dsd-name included-slot))
798                (modified (or (find included-name modified-slots
799                                    :key (lambda (x) (if (atom x) x (car x)))
800                                    :test #'string=)
801                              `(,included-name))))
802           ;; We stash away an alist of accessors to parents' slots
803           ;; that have already been created to avoid conflicts later
804           ;; so that structures with :INCLUDE and :CONC-NAME (and
805           ;; other edge cases) can work as specified.
806           (when (dsd-accessor-name included-slot)
807             ;; the "oldest" (i.e. highest up the tree of inheritance)
808             ;; will prevail, so don't push new ones on if they
809             ;; conflict.
810             (pushnew (cons (dsd-accessor-name included-slot)
811                            (dsd-index included-slot))
812                      (dd-inherited-accessor-alist dd)
813                      :test #'eq :key #'car))
814           (let ((new-slot (parse-1-dsd dd
815                                        modified
816                                        (copy-structure included-slot))))
817             (when (and (neq (dsd-type new-slot) (dsd-type included-slot))
818                        (not (sb!xc:subtypep (dsd-type included-slot)
819                                             (dsd-type new-slot)))
820                        (dsd-safe-p included-slot))
821               (setf (dsd-safe-p new-slot) nil)
822               ;; XXX: notify?
823               )))))))
824 \f
825 ;;;; various helper functions for setting up DEFSTRUCTs
826
827 ;;; This function is called at macroexpand time to compute the INHERITS
828 ;;; vector for a structure type definition.
829 (defun inherits-for-structure (info)
830   (declare (type defstruct-description info))
831   (let* ((include (dd-include info))
832          (superclass-opt (dd-alternate-metaclass info))
833          (super
834           (if include
835               (compiler-layout-or-lose (first include))
836               (classoid-layout (find-classoid
837                                 (or (first superclass-opt)
838                                     'structure-object))))))
839     (case (dd-name info)
840       ((ansi-stream)
841        (concatenate 'simple-vector
842                     (layout-inherits super)
843                     (vector super (classoid-layout (find-classoid 'stream)))))
844       ((fd-stream)
845        (concatenate 'simple-vector
846                     (layout-inherits super)
847                     (vector super
848                             (classoid-layout (find-classoid 'file-stream)))))
849       ((sb!impl::string-input-stream
850         sb!impl::string-output-stream
851         sb!impl::fill-pointer-output-stream)
852        (concatenate 'simple-vector
853                     (layout-inherits super)
854                     (vector super
855                             (classoid-layout (find-classoid 'string-stream)))))
856       (t (concatenate 'simple-vector
857                       (layout-inherits super)
858                       (vector super))))))
859
860 ;;; Do miscellaneous (LOAD EVAL) time actions for the structure
861 ;;; described by DD. Create the class and LAYOUT, checking for
862 ;;; incompatible redefinition. Define those functions which are
863 ;;; sufficiently stereotyped that we can implement them as standard
864 ;;; closures.
865 (defun %defstruct (dd inherits source-location)
866   (declare (type defstruct-description dd))
867
868   ;; We set up LAYOUTs even in the cross-compilation host.
869   (multiple-value-bind (classoid layout old-layout)
870       (ensure-structure-class dd inherits "current" "new")
871     (cond ((not old-layout)
872            (unless (eq (classoid-layout classoid) layout)
873              (register-layout layout)))
874           (t
875            (let ((old-dd (layout-info old-layout)))
876              (when (defstruct-description-p old-dd)
877                (dolist (slot (dd-slots old-dd))
878                  (fmakunbound (dsd-accessor-name slot))
879                  (unless (dsd-read-only slot)
880                    (fmakunbound `(setf ,(dsd-accessor-name slot)))))))
881            (%redefine-defstruct classoid old-layout layout)
882            (setq layout (classoid-layout classoid))))
883     (setf (find-classoid (dd-name dd)) classoid)
884
885     (sb!c:with-source-location (source-location)
886       (setf (layout-source-location layout) source-location))
887
888     ;; Various other operations only make sense on the target SBCL.
889     #-sb-xc-host
890     (%target-defstruct dd layout))
891
892   (values))
893 \f
894 ;;; Return a form describing the writable place used for this slot
895 ;;; in the instance named INSTANCE-NAME.
896 (defun %accessor-place-form (dd dsd instance-name)
897   (let (;; the operator that we'll use to access a typed slot
898         (ref (ecase (dd-type dd)
899                (structure '%instance-ref)
900                (list 'nth-but-with-sane-arg-order)
901                (vector 'aref)))
902         (raw-type (dsd-raw-type dsd)))
903     (if (eq raw-type t) ; if not raw slot
904         `(,ref ,instance-name ,(dsd-index dsd))
905         (let* ((raw-slot-data (find raw-type *raw-slot-data-list*
906                                     :key #'raw-slot-data-raw-type
907                                     :test #'equal))
908                (raw-slot-accessor (raw-slot-data-accessor-name raw-slot-data)))
909           `(,raw-slot-accessor ,instance-name ,(dsd-index dsd))))))
910
911 ;;; Return source transforms for the reader and writer functions of
912 ;;; the slot described by DSD. They should be inline expanded, but
913 ;;; source transforms work faster.
914 (defun slot-accessor-transforms (dd dsd)
915   (let ((accessor-place-form (%accessor-place-form dd dsd
916                                                    `(the ,(dd-name dd) instance)))
917         (dsd-type (dsd-type dsd))
918         (value-the (if (dsd-safe-p dsd) 'truly-the 'the)))
919     (values (sb!c:source-transform-lambda (instance)
920               `(,value-the ,dsd-type ,(subst instance 'instance
921                                              accessor-place-form)))
922             (sb!c:source-transform-lambda (new-value instance)
923               (destructuring-bind (accessor-name &rest accessor-args)
924                   accessor-place-form
925                 (once-only ((new-value new-value)
926                             (instance instance))
927                   `(,(info :setf :inverse accessor-name)
928                      ,@(subst instance 'instance accessor-args)
929                      (the ,dsd-type ,new-value))))))))
930
931 ;;; Return a LAMBDA form which can be used to set a slot.
932 (defun slot-setter-lambda-form (dd dsd)
933   ;; KLUDGE: Evaluating the results of SLOT-ACCESSOR-TRANSFORMS needs
934   ;; a lexenv.
935   (let ((sb!c:*lexenv* (if (boundp 'sb!c:*lexenv*)
936                            sb!c:*lexenv*
937                            (sb!c::make-null-lexenv))))
938     `(lambda (new-value instance)
939        ,(funcall (nth-value 1 (slot-accessor-transforms dd dsd))
940                  '(dummy new-value instance)))))
941
942 ;;; core compile-time setup of any class with a LAYOUT, used even by
943 ;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS weirdosities
944 (defun %compiler-set-up-layout (dd
945                                 &optional
946                                 ;; Several special cases
947                                 ;; (STRUCTURE-OBJECT itself, and
948                                 ;; structures with alternate
949                                 ;; metaclasses) call this function
950                                 ;; directly, and they're all at the
951                                 ;; base of the instance class
952                                 ;; structure, so this is a handy
953                                 ;; default.  (But note
954                                 ;; FUNCALLABLE-STRUCTUREs need
955                                 ;; assistance here)
956                                 (inherits (vector (find-layout t))))
957
958   (multiple-value-bind (classoid layout old-layout)
959       (multiple-value-bind (clayout clayout-p)
960           (info :type :compiler-layout (dd-name dd))
961         (ensure-structure-class dd
962                                 inherits
963                                 (if clayout-p "previously compiled" "current")
964                                 "compiled"
965                                 :compiler-layout clayout))
966     (cond (old-layout
967            (undefine-structure (layout-classoid old-layout))
968            (when (and (classoid-subclasses classoid)
969                       (not (eq layout old-layout)))
970              (collect ((subs))
971                (dohash ((classoid layout) (classoid-subclasses classoid)
972                         :locked t)
973                  (declare (ignore layout))
974                  (undefine-structure classoid)
975                  (subs (classoid-proper-name classoid)))
976                (when (subs)
977                  (warn "removing old subclasses of ~S:~%  ~S"
978                        (classoid-name classoid)
979                        (subs))))))
980           (t
981            (unless (eq (classoid-layout classoid) layout)
982              (register-layout layout :invalidate nil))
983            (setf (find-classoid (dd-name dd)) classoid)))
984
985     ;; At this point the class should be set up in the INFO database.
986     ;; But the logic that enforces this is a little tangled and
987     ;; scattered, so it's not obvious, so let's check.
988     (aver (find-classoid (dd-name dd) nil))
989
990     (setf (info :type :compiler-layout (dd-name dd)) layout))
991
992   (values))
993
994 ;;; Do (COMPILE LOAD EVAL)-time actions for the normal (not
995 ;;; ALTERNATE-LAYOUT) DEFSTRUCT described by DD.
996 (defun %compiler-defstruct (dd inherits)
997   (declare (type defstruct-description dd))
998
999   (%compiler-set-up-layout dd inherits)
1000
1001   (let* ((dtype (dd-declarable-type dd)))
1002
1003     (let ((copier-name (dd-copier-name dd)))
1004       (when copier-name
1005         (sb!xc:proclaim `(ftype (sfunction (,dtype) ,dtype) ,copier-name))))
1006
1007     (let ((predicate-name (dd-predicate-name dd)))
1008       (when predicate-name
1009         (sb!xc:proclaim `(ftype (sfunction (t) boolean) ,predicate-name))
1010         ;; Provide inline expansion (or not).
1011         (ecase (dd-type dd)
1012           ((structure funcallable-structure)
1013            ;; Let the predicate be inlined.
1014            (setf (info :function :inline-expansion-designator predicate-name)
1015                  (lambda ()
1016                    `(lambda (x)
1017                       ;; This dead simple definition works because the
1018                       ;; type system knows how to generate inline type
1019                       ;; tests for instances.
1020                       (typep x ',(dd-name dd))))
1021                  (info :function :inlinep predicate-name)
1022                  :inline))
1023           ((list vector)
1024            ;; Just punt. We could provide inline expansions for :TYPE
1025            ;; LIST and :TYPE VECTOR predicates too, but it'd be a
1026            ;; little messier and we don't bother. (Does anyway use
1027            ;; typed DEFSTRUCTs at all, let alone for high
1028            ;; performance?)
1029            ))))
1030
1031     (dolist (dsd (dd-slots dd))
1032       (let* ((accessor-name (dsd-accessor-name dsd))
1033              (dsd-type (dsd-type dsd)))
1034         (when accessor-name
1035           (setf (info :function :structure-accessor accessor-name) dd)
1036           (let ((inherited (accessor-inherited-data accessor-name dd)))
1037             (cond
1038               ((not inherited)
1039                (multiple-value-bind (reader-designator writer-designator)
1040                    (slot-accessor-transforms dd dsd)
1041                  (sb!xc:proclaim `(ftype (sfunction (,dtype) ,dsd-type)
1042                                    ,accessor-name))
1043                  (setf (info :function :source-transform accessor-name)
1044                        reader-designator)
1045                  (unless (dsd-read-only dsd)
1046                    (let ((setf-accessor-name `(setf ,accessor-name)))
1047                      (sb!xc:proclaim
1048                       `(ftype (sfunction (,dsd-type ,dtype) ,dsd-type)
1049                         ,setf-accessor-name))
1050                      (setf (info :function :source-transform setf-accessor-name)
1051                            writer-designator)))))
1052               ((not (= (cdr inherited) (dsd-index dsd)))
1053                (style-warn "~@<Non-overwritten accessor ~S does not access ~
1054                             slot with name ~S (accessing an inherited slot ~
1055                             instead).~:@>"
1056                            accessor-name
1057                            (dsd-name dsd)))))))))
1058   (values))
1059 \f
1060 ;;;; redefinition stuff
1061
1062 ;;; Compare the slots of OLD and NEW, returning 3 lists of slot names:
1063 ;;;   1. Slots which have moved,
1064 ;;;   2. Slots whose type has changed,
1065 ;;;   3. Deleted slots.
1066 (defun compare-slots (old new)
1067   (let* ((oslots (dd-slots old))
1068          (nslots (dd-slots new))
1069          (onames (mapcar #'dsd-name oslots))
1070          (nnames (mapcar #'dsd-name nslots)))
1071     (collect ((moved)
1072               (retyped))
1073       (dolist (name (intersection onames nnames))
1074         (let ((os (find name oslots :key #'dsd-name :test #'string=))
1075               (ns (find name nslots :key #'dsd-name :test #'string=)))
1076           (unless (sb!xc:subtypep (dsd-type ns) (dsd-type os))
1077             (retyped name))
1078           (unless (and (= (dsd-index os) (dsd-index ns))
1079                        (eq (dsd-raw-type os) (dsd-raw-type ns)))
1080             (moved name))))
1081       (values (moved)
1082               (retyped)
1083               (set-difference onames nnames :test #'string=)))))
1084
1085 ;;; If we are redefining a structure with different slots than in the
1086 ;;; currently loaded version, give a warning and return true.
1087 (defun redefine-structure-warning (classoid old new)
1088   (declare (type defstruct-description old new)
1089            (type classoid classoid)
1090            (ignore classoid))
1091   (let ((name (dd-name new)))
1092     (multiple-value-bind (moved retyped deleted) (compare-slots old new)
1093       (when (or moved retyped deleted)
1094         (warn
1095          "incompatibly redefining slots of structure class ~S~@
1096           Make sure any uses of affected accessors are recompiled:~@
1097           ~@[  These slots were moved to new positions:~%    ~S~%~]~
1098           ~@[  These slots have new incompatible types:~%    ~S~%~]~
1099           ~@[  These slots were deleted:~%    ~S~%~]"
1100          name moved retyped deleted)
1101         t))))
1102
1103 ;;; This function is called when we are incompatibly redefining a
1104 ;;; structure CLASS to have the specified NEW-LAYOUT. We signal an
1105 ;;; error with some proceed options and return the layout that should
1106 ;;; be used.
1107 (defun %redefine-defstruct (classoid old-layout new-layout)
1108   (declare (type classoid classoid)
1109            (type layout old-layout new-layout))
1110   (let ((name (classoid-proper-name classoid)))
1111     (restart-case
1112         (error "~@<attempt to redefine the ~S class ~S incompatibly with the current definition~:@>"
1113                'structure-object
1114                name)
1115       (continue ()
1116        :report (lambda (s)
1117                  (format s
1118                          "~@<Use the new definition of ~S, invalidating ~
1119                           already-loaded code and instances.~@:>"
1120                          name))
1121        (register-layout new-layout))
1122       (recklessly-continue ()
1123        :report (lambda (s)
1124                  (format s
1125                          "~@<Use the new definition of ~S as if it were ~
1126                           compatible, allowing old accessors to use new ~
1127                           instances and allowing new accessors to use old ~
1128                           instances.~@:>"
1129                          name))
1130        ;; classic CMU CL warning: "Any old ~S instances will be in a bad way.
1131        ;; I hope you know what you're doing..."
1132        (register-layout new-layout
1133                         :invalidate nil
1134                         :destruct-layout old-layout))
1135       (clobber-it ()
1136        ;; FIXME: deprecated 2002-10-16, and since it's only interactive
1137        ;; hackery instead of a supported feature, can probably be deleted
1138        ;; in early 2003
1139        :report "(deprecated synonym for RECKLESSLY-CONTINUE)"
1140        (register-layout new-layout
1141                         :invalidate nil
1142                         :destruct-layout old-layout))))
1143   (values))
1144
1145 ;;; This is called when we are about to define a structure class. It
1146 ;;; returns a (possibly new) class object and the layout which should
1147 ;;; be used for the new definition (may be the current layout, and
1148 ;;; also might be an uninstalled forward referenced layout.) The third
1149 ;;; value is true if this is an incompatible redefinition, in which
1150 ;;; case it is the old layout.
1151 (defun ensure-structure-class (info inherits old-context new-context
1152                                     &key compiler-layout)
1153   (multiple-value-bind (class old-layout)
1154       (destructuring-bind
1155           (&optional
1156            name
1157            (class 'structure-classoid)
1158            (constructor 'make-structure-classoid))
1159           (dd-alternate-metaclass info)
1160         (declare (ignore name))
1161         (insured-find-classoid (dd-name info)
1162                                (if (eq class 'structure-classoid)
1163                                    (lambda (x)
1164                                      (sb!xc:typep x 'structure-classoid))
1165                                    (lambda (x)
1166                                      (sb!xc:typep x (classoid-name (find-classoid class)))))
1167                                (fdefinition constructor)))
1168     (setf (classoid-direct-superclasses class)
1169           (case (dd-name info)
1170             ((ansi-stream
1171               fd-stream
1172               sb!impl::string-input-stream sb!impl::string-output-stream
1173               sb!impl::fill-pointer-output-stream)
1174              (list (layout-classoid (svref inherits (1- (length inherits))))
1175                    (layout-classoid (svref inherits (- (length inherits) 2)))))
1176             (t
1177              (list (layout-classoid
1178                     (svref inherits (1- (length inherits))))))))
1179     (let ((new-layout (make-layout :classoid class
1180                                    :inherits inherits
1181                                    :depthoid (length inherits)
1182                                    :length (+ (dd-length info)
1183                                               (dd-raw-length info))
1184                                    :n-untagged-slots (dd-raw-length info)
1185                                    :info info))
1186           (old-layout (or compiler-layout old-layout)))
1187       (cond
1188        ((not old-layout)
1189         (values class new-layout nil))
1190        (;; This clause corresponds to an assertion in REDEFINE-LAYOUT-WARNING
1191         ;; of classic CMU CL. I moved it out to here because it was only
1192         ;; exercised in this code path anyway. -- WHN 19990510
1193         (not (eq (layout-classoid new-layout) (layout-classoid old-layout)))
1194         (error "shouldn't happen: weird state of OLD-LAYOUT?"))
1195        ((not *type-system-initialized*)
1196         (setf (layout-info old-layout) info)
1197         (values class old-layout nil))
1198        ((redefine-layout-warning old-context
1199                                  old-layout
1200                                  new-context
1201                                  (layout-length new-layout)
1202                                  (layout-inherits new-layout)
1203                                  (layout-depthoid new-layout)
1204                                  (layout-n-untagged-slots new-layout))
1205         (values class new-layout old-layout))
1206        (t
1207         (let ((old-info (layout-info old-layout)))
1208           (typecase old-info
1209             ((or defstruct-description)
1210              (cond ((redefine-structure-warning class old-info info)
1211                     (values class new-layout old-layout))
1212                    (t
1213                     (setf (layout-info old-layout) info)
1214                     (values class old-layout nil))))
1215             (null
1216              (setf (layout-info old-layout) info)
1217              (values class old-layout nil))
1218             (t
1219              (error "shouldn't happen! strange thing in LAYOUT-INFO:~%  ~S"
1220                     old-layout)
1221              (values class new-layout old-layout)))))))))
1222
1223 ;;; Blow away all the compiler info for the structure CLASS. Iterate
1224 ;;; over this type, clearing the compiler structure type info, and
1225 ;;; undefining all the associated functions.
1226 (defun undefine-structure (class)
1227   (let ((info (layout-info (classoid-layout class))))
1228     (when (defstruct-description-p info)
1229       (let ((type (dd-name info)))
1230         (remhash type *typecheckfuns*)
1231         (setf (info :type :compiler-layout type) nil)
1232         (undefine-fun-name (dd-copier-name info))
1233         (undefine-fun-name (dd-predicate-name info))
1234         (dolist (slot (dd-slots info))
1235           (let ((fun (dsd-accessor-name slot)))
1236             (unless (accessor-inherited-data fun info)
1237               (undefine-fun-name fun)
1238               (unless (dsd-read-only slot)
1239                 (undefine-fun-name `(setf ,fun)))))))
1240       ;; Clear out the SPECIFIER-TYPE cache so that subsequent
1241       ;; references are unknown types.
1242       (values-specifier-type-cache-clear)))
1243   (values))
1244 \f
1245 ;;; Return a list of pairs (name . index). Used for :TYPE'd
1246 ;;; constructors to find all the names that we have to splice in &
1247 ;;; where. Note that these types don't have a layout, so we can't look
1248 ;;; at LAYOUT-INHERITS.
1249 (defun find-name-indices (defstruct)
1250   (collect ((res))
1251     (let ((infos ()))
1252       (do ((info defstruct
1253                  (typed-structure-info-or-lose (first (dd-include info)))))
1254           ((not (dd-include info))
1255            (push info infos))
1256         (push info infos))
1257
1258       (let ((i 0))
1259         (dolist (info infos)
1260           (incf i (or (dd-offset info) 0))
1261           (when (dd-named info)
1262             (res (cons (dd-name info) i)))
1263           (setq i (dd-length info)))))
1264
1265     (res)))
1266 \f
1267 ;;; These functions are called to actually make a constructor after we
1268 ;;; have processed the arglist. The correct variant (according to the
1269 ;;; DD-TYPE) should be called. The function is defined with the
1270 ;;; specified name and arglist. VARS and TYPES are used for argument
1271 ;;; type declarations. VALUES are the values for the slots (in order.)
1272 ;;;
1273 ;;; This is split three ways because:
1274 ;;;   * LIST & VECTOR structures need "name" symbols stuck in at
1275 ;;;     various weird places, whereas STRUCTURE structures have
1276 ;;;     a LAYOUT slot.
1277 ;;;   * We really want to use LIST to make list structures, instead of
1278 ;;;     MAKE-LIST/(SETF ELT). (We can't in general use VECTOR in an
1279 ;;;     analogous way, since VECTOR makes a SIMPLE-VECTOR and vector-typed
1280 ;;;     structures can have arbitrary subtypes of VECTOR, not necessarily
1281 ;;;     SIMPLE-VECTOR.)
1282 ;;;   * STRUCTURE structures can have raw slots that must also be
1283 ;;;     allocated and indirectly referenced.
1284 (defun create-vector-constructor (dd cons-name arglist vars types values)
1285   (let ((temp (gensym))
1286         (etype (dd-element-type dd)))
1287     `(defun ,cons-name ,arglist
1288        (declare ,@(mapcar (lambda (var type) `(type (and ,type ,etype) ,var))
1289                           vars types))
1290        (let ((,temp (make-array ,(dd-length dd)
1291                                 :element-type ',(dd-element-type dd))))
1292          ,@(mapcar (lambda (x)
1293                      `(setf (aref ,temp ,(cdr x))  ',(car x)))
1294                    (find-name-indices dd))
1295          ,@(mapcar (lambda (dsd value)
1296                      (unless (eq value '.do-not-initialize-slot.)
1297                          `(setf (aref ,temp ,(dsd-index dsd)) ,value)))
1298                    (dd-slots dd) values)
1299          ,temp))))
1300 (defun create-list-constructor (dd cons-name arglist vars types values)
1301   (let ((vals (make-list (dd-length dd) :initial-element nil)))
1302     (dolist (x (find-name-indices dd))
1303       (setf (elt vals (cdr x)) `',(car x)))
1304     (loop for dsd in (dd-slots dd) and val in values do
1305       (setf (elt vals (dsd-index dsd))
1306             (if (eq val '.do-not-initialize-slot.) 0 val)))
1307
1308     `(defun ,cons-name ,arglist
1309        (declare ,@(mapcar (lambda (var type) `(type ,type ,var)) vars types))
1310        (list ,@vals))))
1311 (defun create-structure-constructor (dd cons-name arglist vars types values)
1312   (let* ((instance (gensym "INSTANCE")))
1313     `(defun ,cons-name ,arglist
1314        (declare ,@(mapcar (lambda (var type) `(type ,type ,var))
1315                           vars types))
1316        (let ((,instance (truly-the ,(dd-name dd)
1317                           (%make-instance-with-layout
1318                            (%delayed-get-compiler-layout ,(dd-name dd))))))
1319          ,@(mapcar (lambda (dsd value)
1320                      ;; (Note that we can't in general use the
1321                      ;; ordinary named slot setter function here
1322                      ;; because the slot might be :READ-ONLY, so we
1323                      ;; whip up new LAMBDA representations of slot
1324                      ;; setters for the occasion.)
1325                      (unless (eq value '.do-not-initialize-slot.)
1326                        `(,(slot-setter-lambda-form dd dsd) ,value ,instance)))
1327                    (dd-slots dd)
1328                    values)
1329          ,instance))))
1330
1331 ;;; Create a default (non-BOA) keyword constructor.
1332 (defun create-keyword-constructor (defstruct creator)
1333   (declare (type function creator))
1334   (collect ((arglist (list '&key))
1335             (types)
1336             (vals))
1337     (dolist (slot (dd-slots defstruct))
1338       (let ((dum (gensym))
1339             (name (dsd-name slot)))
1340         (arglist `((,(keywordicate name) ,dum) ,(dsd-default slot)))
1341         (types (dsd-type slot))
1342         (vals dum)))
1343     (funcall creator
1344              defstruct (dd-default-constructor defstruct)
1345              (arglist) (vals) (types) (vals))))
1346
1347 ;;; Given a structure and a BOA constructor spec, call CREATOR with
1348 ;;; the appropriate args to make a constructor.
1349 (defun create-boa-constructor (defstruct boa creator)
1350   (declare (type function creator))
1351   (multiple-value-bind (req opt restp rest keyp keys allowp auxp aux)
1352       (parse-lambda-list (second boa))
1353     (collect ((arglist)
1354               (vars)
1355               (types)
1356               (skipped-vars))
1357       (labels ((get-slot (name)
1358                  (let ((res (find name (dd-slots defstruct)
1359                                   :test #'string=
1360                                   :key #'dsd-name)))
1361                    (if res
1362                        (values (dsd-type res) (dsd-default res))
1363                        (values t nil))))
1364                (do-default (arg)
1365                  (multiple-value-bind (type default) (get-slot arg)
1366                    (arglist `(,arg ,default))
1367                    (vars arg)
1368                    (types type))))
1369         (dolist (arg req)
1370           (arglist arg)
1371           (vars arg)
1372           (types (get-slot arg)))
1373
1374         (when opt
1375           (arglist '&optional)
1376           (dolist (arg opt)
1377             (cond ((consp arg)
1378                    (destructuring-bind
1379                          ;; FIXME: this shares some logic (though not
1380                          ;; code) with the &key case below (and it
1381                          ;; looks confusing) -- factor out the logic
1382                          ;; if possible. - CSR, 2002-04-19
1383                          (name
1384                           &optional
1385                           (def (nth-value 1 (get-slot name)))
1386                           (supplied-test nil supplied-test-p))
1387                        arg
1388                      (arglist `(,name ,def ,@(if supplied-test-p `(,supplied-test) nil)))
1389                      (vars name)
1390                      (types (get-slot name))))
1391                   (t
1392                    (do-default arg)))))
1393
1394         (when restp
1395           (arglist '&rest rest)
1396           (vars rest)
1397           (types 'list))
1398
1399         (when keyp
1400           (arglist '&key)
1401           (dolist (key keys)
1402             (if (consp key)
1403                 (destructuring-bind (wot
1404                                      &optional
1405                                      (def nil def-p)
1406                                      (supplied-test nil supplied-test-p))
1407                     key
1408                   (let ((name (if (consp wot)
1409                                   (destructuring-bind (key var) wot
1410                                     (declare (ignore key))
1411                                     var)
1412                                   wot)))
1413                     (multiple-value-bind (type slot-def)
1414                         (get-slot name)
1415                       (arglist `(,wot ,(if def-p def slot-def)
1416                                  ,@(if supplied-test-p `(,supplied-test) nil)))
1417                       (vars name)
1418                       (types type))))
1419                 (do-default key))))
1420
1421         (when allowp (arglist '&allow-other-keys))
1422
1423         (when auxp
1424           (arglist '&aux)
1425           (dolist (arg aux)
1426             (arglist arg)
1427             (if (proper-list-of-length-p arg 2)
1428               (let ((var (first arg)))
1429                 (vars var)
1430                 (types (get-slot var)))
1431               (skipped-vars (if (consp arg) (first arg) arg))))))
1432
1433       (funcall creator defstruct (first boa)
1434                (arglist) (vars) (types)
1435                (loop for slot in (dd-slots defstruct)
1436                      for name = (dsd-name slot)
1437                      collect (cond ((find name (skipped-vars) :test #'string=)
1438                                     (setf (dsd-safe-p slot) nil)
1439                                     '.do-not-initialize-slot.)
1440                                    ((or (find (dsd-name slot) (vars) :test #'string=)
1441                                         (dsd-default slot)))))))))
1442
1443 ;;; Grovel the constructor options, and decide what constructors (if
1444 ;;; any) to create.
1445 (defun constructor-definitions (defstruct)
1446   (let ((no-constructors nil)
1447         (boas ())
1448         (defaults ())
1449         (creator (ecase (dd-type defstruct)
1450                    (structure #'create-structure-constructor)
1451                    (vector #'create-vector-constructor)
1452                    (list #'create-list-constructor))))
1453     (dolist (constructor (dd-constructors defstruct))
1454       (destructuring-bind (name &optional (boa-ll nil boa-p)) constructor
1455         (declare (ignore boa-ll))
1456         (cond ((not name) (setq no-constructors t))
1457               (boa-p (push constructor boas))
1458               (t (push name defaults)))))
1459
1460     (when no-constructors
1461       (when (or defaults boas)
1462         (error "(:CONSTRUCTOR NIL) combined with other :CONSTRUCTORs"))
1463       (return-from constructor-definitions ()))
1464
1465     (unless (or defaults boas)
1466       (push (symbolicate "MAKE-" (dd-name defstruct)) defaults))
1467
1468     (collect ((res) (names))
1469       (when defaults
1470         (let ((cname (first defaults)))
1471           (setf (dd-default-constructor defstruct) cname)
1472           (res (create-keyword-constructor defstruct creator))
1473           (names cname)
1474           (dolist (other-name (rest defaults))
1475             (res `(setf (fdefinition ',other-name) (fdefinition ',cname)))
1476             (names other-name))))
1477
1478       (dolist (boa boas)
1479         (res (create-boa-constructor defstruct boa creator))
1480         (names (first boa)))
1481
1482       (res `(declaim (ftype
1483                       (sfunction *
1484                                  ,(if (eq (dd-type defstruct) 'structure)
1485                                       (dd-name defstruct)
1486                                       '*))
1487                       ,@(names))))
1488
1489       (res))))
1490 \f
1491 ;;;; instances with ALTERNATE-METACLASS
1492 ;;;;
1493 ;;;; The CMU CL support for structures with ALTERNATE-METACLASS was a
1494 ;;;; fairly general extension embedded in the main DEFSTRUCT code, and
1495 ;;;; the result was an fairly impressive mess as ALTERNATE-METACLASS
1496 ;;;; extension mixed with ANSI CL generality (e.g. :TYPE and :INCLUDE)
1497 ;;;; and CMU CL implementation hairiness (esp. raw slots). This SBCL
1498 ;;;; version is much less ambitious, noticing that ALTERNATE-METACLASS
1499 ;;;; is only used to implement CONDITION, STANDARD-INSTANCE, and
1500 ;;;; GENERIC-FUNCTION, and defining a simple specialized
1501 ;;;; separate-from-DEFSTRUCT macro to provide only enough
1502 ;;;; functionality to support those.
1503 ;;;;
1504 ;;;; KLUDGE: The defining macro here is so specialized that it's ugly
1505 ;;;; in its own way. It also violates once-and-only-once by knowing
1506 ;;;; much about structures and layouts that is already known by the
1507 ;;;; main DEFSTRUCT macro. Hopefully it will go away presently
1508 ;;;; (perhaps when CL:CLASS and SB-PCL:CLASS meet) as per FIXME below.
1509 ;;;; -- WHN 2001-10-28
1510 ;;;;
1511 ;;;; FIXME: There seems to be no good reason to shoehorn CONDITION,
1512 ;;;; STANDARD-INSTANCE, and GENERIC-FUNCTION into mutated structures
1513 ;;;; instead of just implementing them as primitive objects. (This
1514 ;;;; reduced-functionality macro seems pretty close to the
1515 ;;;; functionality of DEFINE-PRIMITIVE-OBJECT..)
1516
1517 (defun make-dd-with-alternate-metaclass (&key (class-name (missing-arg))
1518                                               (superclass-name (missing-arg))
1519                                               (metaclass-name (missing-arg))
1520                                               (dd-type (missing-arg))
1521                                               metaclass-constructor
1522                                               slot-names)
1523   (let* ((dd (make-defstruct-description class-name))
1524          (conc-name (concatenate 'string (symbol-name class-name) "-"))
1525          (dd-slots (let ((reversed-result nil)
1526                          ;; The index starts at 1 for ordinary named
1527                          ;; slots because slot 0 is magical, used for
1528                          ;; the LAYOUT in CONDITIONs and
1529                          ;; FUNCALLABLE-INSTANCEs.  (This is the same
1530                          ;; in ordinary structures too: see (INCF
1531                          ;; DD-LENGTH) in
1532                          ;; PARSE-DEFSTRUCT-NAME-AND-OPTIONS).
1533                          (index 1))
1534                      (dolist (slot-name slot-names)
1535                        (push (make-defstruct-slot-description
1536                               :name slot-name
1537                               :index index
1538                               :accessor-name (symbolicate conc-name slot-name))
1539                              reversed-result)
1540                        (incf index))
1541                      (nreverse reversed-result))))
1542     (case dd-type
1543       ;; We don't support inheritance of alternate metaclass stuff,
1544       ;; and it's not a general-purpose facility, so sanity check our
1545       ;; own code.
1546       (structure
1547        (aver (eq superclass-name 't)))
1548       (funcallable-structure
1549        (aver (eq superclass-name 'function)))
1550       (t (bug "Unknown DD-TYPE in ALTERNATE-METACLASS: ~S" dd-type)))
1551     (setf (dd-alternate-metaclass dd) (list superclass-name
1552                                             metaclass-name
1553                                             metaclass-constructor)
1554           (dd-slots dd) dd-slots
1555           (dd-length dd) (1+ (length slot-names))
1556           (dd-type dd) dd-type)
1557     dd))
1558
1559 ;;; make !DEFSTRUCT-WITH-ALTERNATE-METACLASS compilable by the host
1560 ;;; lisp, installing the information we need to reason about the
1561 ;;; structures (layouts and classoids).
1562 ;;;
1563 ;;; FIXME: we should share the parsing and the DD construction between
1564 ;;; this and the cross-compiler version, but my brain was too small to
1565 ;;; get that right.  -- CSR, 2006-09-14
1566 #+sb-xc-host
1567 (defmacro !defstruct-with-alternate-metaclass
1568     (class-name &key
1569                 (slot-names (missing-arg))
1570                 (boa-constructor (missing-arg))
1571                 (superclass-name (missing-arg))
1572                 (metaclass-name (missing-arg))
1573                 (metaclass-constructor (missing-arg))
1574                 (dd-type (missing-arg))
1575                 predicate
1576                 (runtime-type-checks-p t))
1577
1578   (declare (type (and list (not null)) slot-names))
1579   (declare (type (and symbol (not null))
1580                  boa-constructor
1581                  superclass-name
1582                  metaclass-name
1583                  metaclass-constructor))
1584   (declare (type symbol predicate))
1585   (declare (type (member structure funcallable-structure) dd-type))
1586   (declare (ignore boa-constructor predicate runtime-type-checks-p))
1587
1588   (let* ((dd (make-dd-with-alternate-metaclass
1589               :class-name class-name
1590               :slot-names slot-names
1591               :superclass-name superclass-name
1592               :metaclass-name metaclass-name
1593               :metaclass-constructor metaclass-constructor
1594               :dd-type dd-type)))
1595     `(progn
1596
1597       (eval-when (:compile-toplevel :load-toplevel :execute)
1598         (%compiler-set-up-layout ',dd ',(inherits-for-structure dd))))))
1599
1600 (sb!xc:defmacro !defstruct-with-alternate-metaclass
1601     (class-name &key
1602                 (slot-names (missing-arg))
1603                 (boa-constructor (missing-arg))
1604                 (superclass-name (missing-arg))
1605                 (metaclass-name (missing-arg))
1606                 (metaclass-constructor (missing-arg))
1607                 (dd-type (missing-arg))
1608                 predicate
1609                 (runtime-type-checks-p t))
1610
1611   (declare (type (and list (not null)) slot-names))
1612   (declare (type (and symbol (not null))
1613                  boa-constructor
1614                  superclass-name
1615                  metaclass-name
1616                  metaclass-constructor))
1617   (declare (type symbol predicate))
1618   (declare (type (member structure funcallable-structure) dd-type))
1619
1620   (let* ((dd (make-dd-with-alternate-metaclass
1621               :class-name class-name
1622               :slot-names slot-names
1623               :superclass-name superclass-name
1624               :metaclass-name metaclass-name
1625               :metaclass-constructor metaclass-constructor
1626               :dd-type dd-type))
1627          (dd-slots (dd-slots dd))
1628          (dd-length (1+ (length slot-names)))
1629          (object-gensym (gensym "OBJECT"))
1630          (new-value-gensym (gensym "NEW-VALUE-"))
1631          (delayed-layout-form `(%delayed-get-compiler-layout ,class-name)))
1632     (multiple-value-bind (raw-maker-form raw-reffer-operator)
1633         (ecase dd-type
1634           (structure
1635            (values `(let ((,object-gensym (%make-instance ,dd-length)))
1636                       (setf (%instance-layout ,object-gensym)
1637                             ,delayed-layout-form)
1638                       ,object-gensym)
1639                    '%instance-ref))
1640           (funcallable-structure
1641            (values `(let ((,object-gensym
1642                            (%make-funcallable-instance ,dd-length)))
1643                       (setf (%funcallable-instance-layout ,object-gensym)
1644                             ,delayed-layout-form)
1645                       ,object-gensym)
1646                    '%funcallable-instance-info)))
1647       `(progn
1648
1649          (eval-when (:compile-toplevel :load-toplevel :execute)
1650            (%compiler-set-up-layout ',dd ',(inherits-for-structure dd)))
1651
1652          ;; slot readers and writers
1653          (declaim (inline ,@(mapcar #'dsd-accessor-name dd-slots)))
1654          ,@(mapcar (lambda (dsd)
1655                      `(defun ,(dsd-accessor-name dsd) (,object-gensym)
1656                         ,@(when runtime-type-checks-p
1657                             `((declare (type ,class-name ,object-gensym))))
1658                         (,raw-reffer-operator ,object-gensym
1659                                               ,(dsd-index dsd))))
1660                    dd-slots)
1661          (declaim (inline ,@(mapcar (lambda (dsd)
1662                                       `(setf ,(dsd-accessor-name dsd)))
1663                                     dd-slots)))
1664          ,@(mapcar (lambda (dsd)
1665                      `(defun (setf ,(dsd-accessor-name dsd)) (,new-value-gensym
1666                                                               ,object-gensym)
1667                         ,@(when runtime-type-checks-p
1668                             `((declare (type ,class-name ,object-gensym))))
1669                         (setf (,raw-reffer-operator ,object-gensym
1670                                                     ,(dsd-index dsd))
1671                               ,new-value-gensym)))
1672                    dd-slots)
1673
1674          ;; constructor
1675          (defun ,boa-constructor ,slot-names
1676            (let ((,object-gensym ,raw-maker-form))
1677              ,@(mapcar (lambda (slot-name)
1678                          (let ((dsd (find (symbol-name slot-name) dd-slots
1679                                           :key (lambda (x)
1680                                                  (symbol-name (dsd-name x)))
1681                                           :test #'string=)))
1682                            ;; KLUDGE: bug 117 bogowarning.  Neither
1683                            ;; DECLAREing the type nor TRULY-THE cut
1684                            ;; the mustard -- it still gives warnings.
1685                            (enforce-type dsd defstruct-slot-description)
1686                            `(setf (,(dsd-accessor-name dsd) ,object-gensym)
1687                                   ,slot-name)))
1688                        slot-names)
1689              ,object-gensym))
1690
1691          ;; predicate
1692          ,@(when predicate
1693              ;; Just delegate to the compiler's type optimization
1694              ;; code, which knows how to generate inline type tests
1695              ;; for the whole CMU CL INSTANCE menagerie.
1696              `(defun ,predicate (,object-gensym)
1697                 (typep ,object-gensym ',class-name)))))))
1698 \f
1699 ;;;; finalizing bootstrapping
1700
1701 ;;; Set up DD and LAYOUT for STRUCTURE-OBJECT class itself.
1702 ;;;
1703 ;;; Ordinary structure classes effectively :INCLUDE STRUCTURE-OBJECT
1704 ;;; when they have no explicit :INCLUDEs, so (1) it needs to be set up
1705 ;;; before we can define ordinary structure classes, and (2) it's
1706 ;;; special enough (and simple enough) that we just build it by hand
1707 ;;; instead of trying to generalize the ordinary DEFSTRUCT code.
1708 (defun !set-up-structure-object-class ()
1709   (let ((dd (make-defstruct-description 'structure-object)))
1710     (setf
1711      ;; Note: This has an ALTERNATE-METACLASS only because of blind
1712      ;; clueless imitation of the CMU CL code -- dunno if or why it's
1713      ;; needed. -- WHN
1714      (dd-alternate-metaclass dd) '(t)
1715      (dd-slots dd) nil
1716      (dd-length dd) 1
1717      (dd-type dd) 'structure)
1718     (%compiler-set-up-layout dd)))
1719 (!set-up-structure-object-class)
1720
1721 ;;; early structure predeclarations: Set up DD and LAYOUT for ordinary
1722 ;;; (non-ALTERNATE-METACLASS) structures which are needed early.
1723 (dolist (args
1724          '#.(sb-cold:read-from-file
1725              "src/code/early-defstruct-args.lisp-expr"))
1726   (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
1727               (first args)
1728               (rest args)))
1729          (inherits (inherits-for-structure dd)))
1730     (%compiler-defstruct dd inherits)))
1731
1732 ;;; finding these beasts
1733 (defun find-defstruct-description (name &optional (errorp t))
1734   (let ((info (layout-info (classoid-layout (find-classoid name errorp)))))
1735     (if (defstruct-description-p info)
1736         info
1737         (when errorp
1738           (error "No DEFSTRUCT-DESCRIPTION for ~S." name)))))
1739
1740 (/show0 "code/defstruct.lisp end of file")