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