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