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