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