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