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