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