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