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