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