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