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