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