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