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