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