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