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