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