1 ;;;; that part of DEFSTRUCT implementation which is needed not just
2 ;;;; in the target Lisp but also in the cross-compilation host
4 ;;;; This software is part of the SBCL system. See the README file for
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.
13 (in-package "SB!KERNEL")
15 (/show0 "code/defstruct.lisp 15")
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)))
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))
29 (defun compiler-layout-ready-p (name)
30 (let ((layout (info :type :compiler-layout name)))
31 (and layout (typep (layout-info layout) 'defstruct-description))))
33 (sb!xc:defmacro %make-structure-instance-macro (dd slot-specs &rest slot-vars)
34 `(truly-the ,(dd-name dd)
35 ,(if (compiler-layout-ready-p (dd-name dd))
36 `(%make-structure-instance ,dd ,slot-specs ,@slot-vars)
37 ;; Non-toplevel defstructs don't have a layout at compile time,
38 ;; so we need to construct the actual function at runtime -- but
39 ;; we cache it at the call site, so that we don't perform quite
41 `(let* ((cell (load-time-value (list nil)))
44 (funcall fun ,@slot-vars)
45 (funcall (setf (car cell)
46 (%make-structure-instance-allocator ,dd ,slot-specs))
49 (declaim (ftype (sfunction (defstruct-description list) function)
50 %Make-structure-instance-allocator))
51 (defun %make-structure-instance-allocator (dd slot-specs)
52 (let ((vars (make-gensym-list (length slot-specs))))
53 (values (compile nil `(lambda (,@vars)
54 (%make-structure-instance-macro ,dd ',slot-specs ,@vars))))))
56 ;;; Delay looking for compiler-layout until the constructor is being
57 ;;; compiled, since it doesn't exist until after the EVAL-WHEN
58 ;;; (COMPILE) stuff is compiled. (Or, in the oddball case when
59 ;;; DEFSTRUCT is executing in a non-toplevel context, the
60 ;;; compiler-layout still doesn't exist at compilation time, and we
61 ;;; delay still further.)
62 (sb!xc:defmacro %delayed-get-compiler-layout (name)
63 (let ((layout (info :type :compiler-layout name)))
65 ;; ordinary case: When the DEFSTRUCT is at top level,
66 ;; then EVAL-WHEN (COMPILE) stuff will have set up the
67 ;; layout for us to use.
68 (unless (typep (layout-info layout) 'defstruct-description)
69 (error "Class is not a structure class: ~S" name))
72 ;; KLUDGE: In the case that DEFSTRUCT is not at top-level
73 ;; the layout doesn't exist at compile time. In that case
74 ;; we laboriously look it up at run time. This code will
75 ;; run on every constructor call and will likely be quite
76 ;; slow, so if anyone cares about performance of
77 ;; non-toplevel DEFSTRUCTs, it should be rewritten to be
78 ;; cleverer. -- WHN 2002-10-23
80 "implementation limitation: ~
81 Non-toplevel DEFSTRUCT constructors are slow.")
82 (with-unique-names (layout)
83 `(let ((,layout (info :type :compiler-layout ',name)))
84 (unless (typep (layout-info ,layout) 'defstruct-description)
85 (error "Class is not a structure class: ~S" ',name))
88 ;;; re. %DELAYED-GET-COMPILER-LAYOUT and COMPILE-TIME-FIND-LAYOUT, above..
90 ;;; FIXME: Perhaps both should be defined with DEFMACRO-MUNDANELY?
91 ;;; FIXME: Do we really need both? If so, their names and implementations
92 ;;; should probably be tweaked to be more parallel.
94 ;;;; DEFSTRUCT-DESCRIPTION
96 ;;; The DEFSTRUCT-DESCRIPTION structure holds compile-time information
97 ;;; about a structure type.
98 (def!struct (defstruct-description
100 (:make-load-form-fun just-dump-it-normally)
101 #-sb-xc-host (:pure t)
102 (:constructor make-defstruct-description
104 (conc-name (symbolicate name "-"))
105 (copier-name (symbolicate "COPY-" name))
106 (predicate-name (symbolicate name "-P")))))
107 ;; name of the structure
108 (name (missing-arg) :type symbol :read-only t)
109 ;; documentation on the structure
110 (doc nil :type (or string null))
111 ;; prefix for slot names. If NIL, none.
112 (conc-name nil :type (or symbol null))
113 ;; the name of the primary standard keyword constructor, or NIL if none
114 (default-constructor nil :type (or symbol null))
115 ;; all the explicit :CONSTRUCTOR specs, with name defaulted
116 (constructors () :type list)
117 ;; name of copying function
118 (copier-name nil :type (or symbol null))
119 ;; name of type predicate
120 (predicate-name nil :type (or symbol null))
121 ;; the arguments to the :INCLUDE option, or NIL if no included
123 (include nil :type list)
124 ;; properties used to define structure-like classes with an
125 ;; arbitrary superclass and that may not have STRUCTURE-CLASS as the
126 ;; metaclass. Syntax is:
127 ;; (superclass-name metaclass-name metaclass-constructor)
128 (alternate-metaclass nil :type list)
129 ;; a list of DEFSTRUCT-SLOT-DESCRIPTION objects for all slots
130 ;; (including included ones)
131 (slots () :type list)
132 ;; a list of (NAME . INDEX) pairs for accessors of included structures
133 (inherited-accessor-alist () :type list)
134 ;; number of elements we've allocated (See also RAW-LENGTH, which is not
135 ;; included in LENGTH.)
136 (length 0 :type index)
137 ;; General kind of implementation.
138 (type 'structure :type (member structure vector list
139 funcallable-structure))
141 ;; The next three slots are for :TYPE'd structures (which aren't
142 ;; classes, DD-CLASS-P = NIL)
144 ;; vector element type
146 ;; T if :NAMED was explicitly specified, NIL otherwise
147 (named nil :type boolean)
148 ;; any INITIAL-OFFSET option on this direct type
149 (offset nil :type (or index null))
151 ;; the argument to the PRINT-FUNCTION option, or NIL if a
152 ;; PRINT-FUNCTION option was given with no argument, or 0 if no
153 ;; PRINT-FUNCTION option was given
154 (print-function 0 :type (or cons symbol (member 0)))
155 ;; the argument to the PRINT-OBJECT option, or NIL if a PRINT-OBJECT
156 ;; option was given with no argument, or 0 if no PRINT-OBJECT option
158 (print-object 0 :type (or cons symbol (member 0)))
159 ;; The number of untagged slots at the end.
160 (raw-length 0 :type index)
161 ;; the value of the :PURE option, or :UNSPECIFIED. This is only
162 ;; meaningful if DD-CLASS-P = T.
163 (pure :unspecified :type (member t nil :substructure :unspecified)))
164 (def!method print-object ((x defstruct-description) stream)
165 (print-unreadable-object (x stream :type t)
166 (prin1 (dd-name x) stream)))
168 ;;; Does DD describe a structure with a class?
169 (defun dd-class-p (dd)
171 '(structure funcallable-structure)))
173 ;;; a type name which can be used when declaring things which operate
174 ;;; on structure instances
175 (defun dd-declarable-type (dd)
177 ;; Native classes are known to the type system, and we can
178 ;; declare them as types.
180 ;; Structures layered on :TYPE LIST or :TYPE VECTOR aren't part
181 ;; of the type system, so all we can declare is the underlying
182 ;; LIST or VECTOR type.
185 (defun dd-layout-or-lose (dd)
186 (compiler-layout-or-lose (dd-name dd)))
188 ;;;; DEFSTRUCT-SLOT-DESCRIPTION
190 ;;; A DEFSTRUCT-SLOT-DESCRIPTION holds compile-time information about
191 ;;; a structure slot.
192 (def!struct (defstruct-slot-description
193 (:make-load-form-fun just-dump-it-normally)
196 #-sb-xc-host (:pure t))
199 ;; its position in the implementation sequence
200 (index (missing-arg) :type fixnum)
201 ;; the name of the accessor function
203 ;; (CMU CL had extra complexity here ("..or NIL if this accessor has
204 ;; the same name as an inherited accessor (which we don't want to
205 ;; shadow)") but that behavior doesn't seem to be specified by (or
206 ;; even particularly consistent with) ANSI, so it's gone in SBCL.)
208 default ; default value expression
209 (type t) ; declared type specifier
210 (safe-p t :type boolean) ; whether the slot is known to be
211 ; always of the specified type
212 ;; If this object does not describe a raw slot, this value is T.
214 ;; If this object describes a raw slot, this value is the type of the
215 ;; value that the raw slot holds.
216 (raw-type t :type (member t single-float double-float
217 #!+long-float long-float
218 complex-single-float complex-double-float
219 #!+long-float complex-long-float
221 (read-only nil :type (member t nil)))
222 (def!method print-object ((x defstruct-slot-description) stream)
223 (print-unreadable-object (x stream :type t)
224 (prin1 (dsd-name x) stream)))
226 ;;;; typed (non-class) structures
228 ;;; Return a type specifier we can use for testing :TYPE'd structures.
229 (defun dd-lisp-type (defstruct)
230 (ecase (dd-type defstruct)
232 (vector `(simple-array ,(dd-element-type defstruct) (*)))))
234 ;;;; shared machinery for inline and out-of-line slot accessor functions
236 ;;; Classic comment preserved for entertainment value:
238 ;;; "A lie can travel halfway round the world while the truth is
239 ;;; putting on its shoes." -- Mark Twain
241 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
243 ;; information about how a slot of a given DSD-RAW-TYPE is to be accessed
244 (defstruct raw-slot-data
245 ;; the raw slot type, or T for a non-raw slot
247 ;; (Non-raw slots are in the ordinary place you'd expect, directly
248 ;; indexed off the instance pointer. Raw slots are indexed from the end
249 ;; of the instance and skipped by GC.)
250 (raw-type (missing-arg) :type (or symbol cons) :read-only t)
251 ;; What operator is used to access a slot of this type?
252 (accessor-name (missing-arg) :type symbol :read-only t)
253 (init-vop (missing-arg) :type symbol :read-only t)
254 ;; How many words are each value of this type?
255 (n-words (missing-arg) :type (and index (integer 1)) :read-only t)
256 ;; Necessary alignment in units of words. Note that instances
257 ;; themselves are aligned by exactly two words, so specifying more
258 ;; than two words here would not work.
259 (alignment 1 :type (integer 1 2) :read-only t))
261 (defvar *raw-slot-data-list*
265 (let ((double-float-alignment
266 ;; white list of architectures that can load unaligned doubles:
267 #!+(or x86 x86-64 ppc) 1
268 ;; at least sparc, mips and alpha can't:
269 #!-(or x86 x86-64 ppc) 2))
271 (make-raw-slot-data :raw-type 'sb!vm:word
272 :accessor-name '%raw-instance-ref/word
273 :init-vop 'sb!vm::raw-instance-init/word
275 (make-raw-slot-data :raw-type 'single-float
276 :accessor-name '%raw-instance-ref/single
277 :init-vop 'sb!vm::raw-instance-init/single
278 ;; KLUDGE: On 64 bit architectures, we
279 ;; could pack two SINGLE-FLOATs into the
280 ;; same word if raw slots were indexed
281 ;; using bytes instead of words. However,
282 ;; I don't personally find optimizing
283 ;; SINGLE-FLOAT memory usage worthwile
284 ;; enough. And the other datatype that
285 ;; would really benefit is (UNSIGNED-BYTE
286 ;; 32), but that is a subtype of FIXNUM, so
287 ;; we store it unraw anyway. :-( -- DFL
289 (make-raw-slot-data :raw-type 'double-float
290 :accessor-name '%raw-instance-ref/double
291 :init-vop 'sb!vm::raw-instance-init/double
292 :alignment double-float-alignment
293 :n-words (/ 8 sb!vm:n-word-bytes))
294 (make-raw-slot-data :raw-type 'complex-single-float
295 :accessor-name '%raw-instance-ref/complex-single
296 :init-vop 'sb!vm::raw-instance-init/complex-single
297 :n-words (/ 8 sb!vm:n-word-bytes))
298 (make-raw-slot-data :raw-type 'complex-double-float
299 :accessor-name '%raw-instance-ref/complex-double
300 :init-vop 'sb!vm::raw-instance-init/complex-double
301 :alignment double-float-alignment
302 :n-words (/ 16 sb!vm:n-word-bytes))
304 (make-raw-slot-data :raw-type long-float
305 :accessor-name '%raw-instance-ref/long
306 :init-vop 'sb!vm::raw-instance-init/long
307 :n-words #!+x86 3 #!+sparc 4)
309 (make-raw-slot-data :raw-type complex-long-float
310 :accessor-name '%raw-instance-ref/complex-long
311 :init-vop 'sb!vm::raw-instance-init/complex-long
312 :n-words #!+x86 6 #!+sparc 8)))))
313 (defun raw-slot-words (type)
314 (let ((rsd (find type *raw-slot-data-list* :key #'raw-slot-data-raw-type)))
316 (raw-slot-data-n-words rsd)
317 (error "Invalid raw slot type: ~S" type))))
319 ;;;; the legendary DEFSTRUCT macro itself (both CL:DEFSTRUCT and its
320 ;;;; close personal friend SB!XC:DEFSTRUCT)
322 ;;; Return a list of forms to install PRINT and MAKE-LOAD-FORM funs,
323 ;;; mentioning them in the expansion so that they can be compiled.
324 (defun class-method-definitions (defstruct)
325 (let ((name (dd-name defstruct)))
327 ;; KLUDGE: There's a FIND-CLASS DEFTRANSFORM for constant
328 ;; class names which creates fast but non-cold-loadable,
329 ;; non-compact code. In this context, we'd rather have
330 ;; compact, cold-loadable code. -- WHN 19990928
331 (declare (notinline find-classoid))
332 ,@(let ((pf (dd-print-function defstruct))
333 (po (dd-print-object defstruct))
336 ;; Giving empty :PRINT-OBJECT or :PRINT-FUNCTION options
337 ;; leaves PO or PF equal to NIL. The user-level effect is
338 ;; to generate a PRINT-OBJECT method specialized for the type,
339 ;; implementing the default #S structure-printing behavior.
340 (when (or (eq pf nil) (eq po nil))
341 (setf pf '(default-structure-print)
343 (flet (;; Given an arg from a :PRINT-OBJECT or :PRINT-FUNCTION
344 ;; option, return the value to pass as an arg to FUNCTION.
346 (destructuring-bind (fun-name) oarg
348 (cond ((not (eql pf 0))
349 `((def!method print-object ((,x ,name) ,s)
350 (funcall #',(farg pf)
353 *current-level-in-print*))))
355 `((def!method print-object ((,x ,name) ,s)
356 (funcall #',(farg po) ,x ,s))))
358 ,@(let ((pure (dd-pure defstruct)))
360 `((setf (layout-pure (classoid-layout
361 (find-classoid ',name)))
363 ((eq pure :substructure)
364 `((setf (layout-pure (classoid-layout
365 (find-classoid ',name)))
367 ,@(let ((def-con (dd-default-constructor defstruct)))
368 (when (and def-con (not (dd-alternate-metaclass defstruct)))
369 `((setf (structure-classoid-constructor (find-classoid ',name))
372 ;;; shared logic for host macroexpansion for SB!XC:DEFSTRUCT and
373 ;;; cross-compiler macroexpansion for CL:DEFSTRUCT
374 (defmacro !expander-for-defstruct (name-and-options
376 expanding-into-code-for-xc-host-p)
377 `(let ((name-and-options ,name-and-options)
378 (slot-descriptions ,slot-descriptions)
379 (expanding-into-code-for-xc-host-p
380 ,expanding-into-code-for-xc-host-p))
381 (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
386 (let ((inherits (inherits-for-structure dd)))
388 ;; Note we intentionally enforce package locks and
389 ;; call %DEFSTRUCT first, and especially before
390 ;; %COMPILER-DEFSTRUCT. %DEFSTRUCT has the tests (and
391 ;; resulting CERROR) for collisions with LAYOUTs which
392 ;; already exist in the runtime. If there are any
393 ;; collisions, we want the user's response to CERROR
394 ;; to control what happens. Especially, if the user
395 ;; responds to the collision with ABORT, we don't want
396 ;; %COMPILER-DEFSTRUCT to modify the definition of the
398 (with-single-package-locked-error
399 (:symbol ',name "defining ~A as a structure"))
400 (%defstruct ',dd ',inherits (sb!c:source-location))
401 (eval-when (:compile-toplevel :load-toplevel :execute)
402 (%compiler-defstruct ',dd ',inherits))
403 ,@(unless expanding-into-code-for-xc-host-p
404 (append ;; FIXME: We've inherited from CMU CL nonparallel
405 ;; code for creating copiers for typed and untyped
406 ;; structures. This should be fixed.
407 ;(copier-definition dd)
408 (constructor-definitions dd)
409 (class-method-definitions dd)))
412 (with-single-package-locked-error
413 (:symbol ',name "defining ~A as a structure"))
414 (eval-when (:compile-toplevel :load-toplevel :execute)
415 (setf (info :typed-structure :info ',name) ',dd))
416 (eval-when (:load-toplevel :execute)
417 (setf (info :source-location :typed-structure ',name)
418 (sb!c:source-location)))
419 ,@(unless expanding-into-code-for-xc-host-p
420 (append (typed-accessor-definitions dd)
421 (typed-predicate-definitions dd)
422 (typed-copier-definitions dd)
423 (constructor-definitions dd)
425 `((setf (fdocumentation ',(dd-name dd) 'structure)
429 (sb!xc:defmacro defstruct (name-and-options &rest slot-descriptions)
431 "DEFSTRUCT {Name | (Name Option*)} {Slot | (Slot [Default] {Key Value}*)}
432 Define the structure type Name. Instances are created by MAKE-<name>,
433 which takes &KEY arguments allowing initial slot values to the specified.
434 A SETF'able function <name>-<slot> is defined for each slot to read and
435 write slot values. <name>-p is a type predicate.
437 Popular DEFSTRUCT options (see manual for others):
441 Specify the name for the constructor or predicate.
443 (:CONSTRUCTOR Name Lambda-List)
444 Specify the name and arguments for a BOA constructor
445 (which is more efficient when keyword syntax isn't necessary.)
447 (:INCLUDE Supertype Slot-Spec*)
448 Make this type a subtype of the structure type Supertype. The optional
449 Slot-Specs override inherited slot options.
454 Asserts that the value of this slot is always of the specified type.
457 If true, no setter function is defined for this slot."
458 (!expander-for-defstruct name-and-options slot-descriptions nil))
460 (defmacro sb!xc:defstruct (name-and-options &rest slot-descriptions)
462 "Cause information about a target structure to be built into the
464 (!expander-for-defstruct name-and-options slot-descriptions t))
466 ;;;; functions to generate code for various parts of DEFSTRUCT definitions
468 ;;; First, a helper to determine whether a name names an inherited
470 (defun accessor-inherited-data (name defstruct)
471 (assoc name (dd-inherited-accessor-alist defstruct) :test #'eq))
473 ;;; Return a list of forms which create a predicate function for a
475 (defun typed-predicate-definitions (defstruct)
476 (let ((name (dd-name defstruct))
477 (predicate-name (dd-predicate-name defstruct))
479 (when (and predicate-name (dd-named defstruct))
480 (let ((ltype (dd-lisp-type defstruct))
481 (name-index (cdr (car (last (find-name-indices defstruct))))))
482 `((defun ,predicate-name (,argname)
483 (and (typep ,argname ',ltype)
485 ((subtypep ltype 'list)
486 `(do ((head (the ,ltype ,argname) (cdr head))
488 ((or (not (consp head)) (= i ,name-index))
489 (and (consp head) (eq ',name (car head))))))
490 ((subtypep ltype 'vector)
491 `(and (= (length (the ,ltype ,argname))
492 ,(dd-length defstruct))
493 (eq ',name (aref (the ,ltype ,argname) ,name-index))))
494 (t (bug "Uncatered-for lisp type in typed DEFSTRUCT: ~S."
497 ;;; Return a list of forms to create a copier function of a typed DEFSTRUCT.
498 (defun typed-copier-definitions (defstruct)
499 (when (dd-copier-name defstruct)
500 `((setf (fdefinition ',(dd-copier-name defstruct)) #'copy-seq)
501 (declaim (ftype function ,(dd-copier-name defstruct))))))
503 ;;; Return a list of function definitions for accessing and setting
504 ;;; the slots of a typed DEFSTRUCT. The functions are proclaimed to be
505 ;;; inline, and the types of their arguments and results are declared
506 ;;; as well. We count on the compiler to do clever things with ELT.
507 (defun typed-accessor-definitions (defstruct)
509 (let ((ltype (dd-lisp-type defstruct)))
510 (dolist (slot (dd-slots defstruct))
511 (let ((name (dsd-accessor-name slot))
512 (index (dsd-index slot))
513 (slot-type `(and ,(dsd-type slot)
514 ,(dd-element-type defstruct))))
515 (let ((inherited (accessor-inherited-data name defstruct)))
518 (stuff `(declaim (inline ,name ,@(unless (dsd-read-only slot)
520 ;; FIXME: The arguments in the next two DEFUNs should
521 ;; be gensyms. (Otherwise e.g. if NEW-VALUE happened to
522 ;; be the name of a special variable, things could get
524 (stuff `(defun ,name (structure)
525 (declare (type ,ltype structure))
526 (the ,slot-type (elt structure ,index))))
527 (unless (dsd-read-only slot)
529 `(defun (setf ,name) (new-value structure)
530 (declare (type ,ltype structure) (type ,slot-type new-value))
531 (setf (elt structure ,index) new-value)))))
532 ((not (= (cdr inherited) index))
533 (style-warn "~@<Non-overwritten accessor ~S does not access ~
534 slot with name ~S (accessing an inherited slot ~
535 instead).~:@>" name (dsd-name slot))))))))
540 (defun require-no-print-options-so-far (defstruct)
541 (unless (and (eql (dd-print-function defstruct) 0)
542 (eql (dd-print-object defstruct) 0))
543 (error "No more than one of the following options may be specified:
544 :PRINT-FUNCTION, :PRINT-OBJECT, :TYPE")))
546 ;;; Parse a single DEFSTRUCT option and store the results in DD.
547 (defun parse-1-dd-option (option dd)
548 (let ((args (rest option))
552 (destructuring-bind (&optional conc-name) args
553 (setf (dd-conc-name dd)
554 (if (symbolp conc-name)
556 (make-symbol (string conc-name))))))
558 (destructuring-bind (&optional (cname (symbolicate "MAKE-" name))
561 (push (cons cname stuff) (dd-constructors dd))))
563 (destructuring-bind (&optional (copier (symbolicate "COPY-" name)))
565 (setf (dd-copier-name dd) copier)))
567 (destructuring-bind (&optional (predicate-name (symbolicate name "-P")))
569 (setf (dd-predicate-name dd) predicate-name)))
571 (when (dd-include dd)
572 (error "more than one :INCLUDE option"))
573 (setf (dd-include dd) args))
575 (require-no-print-options-so-far dd)
576 (setf (dd-print-function dd)
577 (the (or symbol cons) args)))
579 (require-no-print-options-so-far dd)
580 (setf (dd-print-object dd)
581 (the (or symbol cons) args)))
583 (destructuring-bind (type) args
584 (cond ((member type '(list vector))
585 (setf (dd-element-type dd) t)
586 (setf (dd-type dd) type))
587 ((and (consp type) (eq (first type) 'vector))
588 (destructuring-bind (vector vtype) type
589 (declare (ignore vector))
590 (setf (dd-element-type dd) vtype)
591 (setf (dd-type dd) 'vector)))
593 (error "~S is a bad :TYPE for DEFSTRUCT." type)))))
595 (error "The DEFSTRUCT option :NAMED takes no arguments."))
597 (destructuring-bind (offset) args
598 (setf (dd-offset dd) offset)))
600 (destructuring-bind (fun) args
601 (setf (dd-pure dd) fun)))
602 (t (error "unknown DEFSTRUCT option:~% ~S" option)))))
604 ;;; Given name and options, return a DD holding that info.
605 (defun parse-defstruct-name-and-options (name-and-options)
606 (destructuring-bind (name &rest options) name-and-options
607 (aver name) ; A null name doesn't seem to make sense here.
608 (let ((dd (make-defstruct-description name)))
609 (dolist (option options)
610 (cond ((eq option :named)
611 (setf (dd-named dd) t))
613 (parse-1-dd-option option dd))
614 ((member option '(:conc-name :constructor :copier :predicate))
615 (parse-1-dd-option (list option) dd))
617 (error "unrecognized DEFSTRUCT option: ~S" option))))
622 (error ":OFFSET can't be specified unless :TYPE is specified."))
623 (unless (dd-include dd)
624 ;; FIXME: It'd be cleaner to treat no-:INCLUDE as defaulting
625 ;; to :INCLUDE STRUCTURE-OBJECT, and then let the general-case
626 ;; (INCF (DD-LENGTH DD) (DD-LENGTH included-DD)) logic take
627 ;; care of this. (Except that the :TYPE VECTOR and :TYPE
628 ;; LIST cases, with their :NAMED and un-:NAMED flavors,
629 ;; make that messy, alas.)
630 (incf (dd-length dd))))
632 (require-no-print-options-so-far dd)
634 (incf (dd-length dd)))
635 (let ((offset (dd-offset dd)))
636 (when offset (incf (dd-length dd) offset)))))
638 (when (dd-include dd)
639 (frob-dd-inclusion-stuff dd))
643 ;;; Given name and options and slot descriptions (and possibly doc
644 ;;; string at the head of slot descriptions) return a DD holding that
646 (defun parse-defstruct-name-and-options-and-slot-descriptions
647 (name-and-options slot-descriptions)
648 (let ((result (parse-defstruct-name-and-options (if (atom name-and-options)
649 (list name-and-options)
651 (when (stringp (car slot-descriptions))
652 (setf (dd-doc result) (pop slot-descriptions)))
653 (dolist (slot-description slot-descriptions)
654 (allocate-1-slot result (parse-1-dsd result slot-description)))
657 ;;;; stuff to parse slot descriptions
659 ;;; Parse a slot description for DEFSTRUCT, add it to the description
660 ;;; and return it. If supplied, SLOT is a pre-initialized DSD
661 ;;; that we modify to get the new slot. This is supplied when handling
663 (defun parse-1-dsd (defstruct spec &optional
664 (slot (make-defstruct-slot-description :name ""
667 (multiple-value-bind (name default default-p type type-p read-only ro-p)
670 (when (keywordp spec)
671 (style-warn "Keyword slot name indicates probable syntax ~
672 error in DEFSTRUCT: ~S."
678 &optional (default nil default-p)
679 &key (type nil type-p) (read-only nil ro-p))
683 (uncross type) type-p
685 (t (error 'simple-program-error
686 :format-control "in DEFSTRUCT, ~S is not a legal slot ~
688 :format-arguments (list spec))))
690 (when (find name (dd-slots defstruct)
692 :key (lambda (x) (symbol-name (dsd-name x))))
693 (error 'simple-program-error
694 :format-control "duplicate slot name ~S"
695 :format-arguments (list name)))
696 (setf (dsd-name slot) name)
697 (setf (dd-slots defstruct) (nconc (dd-slots defstruct) (list slot)))
699 (let ((accessor-name (if (dd-conc-name defstruct)
700 (symbolicate (dd-conc-name defstruct) name)
702 (predicate-name (dd-predicate-name defstruct)))
703 (setf (dsd-accessor-name slot) accessor-name)
704 (when (eql accessor-name predicate-name)
705 ;; Some adventurous soul has named a slot so that its accessor
706 ;; collides with the structure type predicate. ANSI doesn't
707 ;; specify what to do in this case. As of 2001-09-04, Martin
708 ;; Atzmueller reports that CLISP and Lispworks both give
709 ;; priority to the slot accessor, so that the predicate is
710 ;; overwritten. We might as well do the same (as well as
711 ;; signalling a warning).
713 "~@<The structure accessor name ~S is the same as the name of the ~
714 structure type predicate. ANSI doesn't specify what to do in ~
715 this case. We'll overwrite the type predicate with the slot ~
716 accessor, but you can't rely on this behavior, so it'd be wise to ~
717 remove the ambiguity in your code.~@:>"
719 (setf (dd-predicate-name defstruct) nil))
720 ;; FIXME: It would be good to check for name collisions here, but
723 ;;x(when (and (fboundp accessor-name)
724 ;;x (not (accessor-inherited-data accessor-name defstruct)))
725 ;;x (style-warn "redefining ~S in DEFSTRUCT" accessor-name)))
726 ;; which was done until sbcl-0.8.11.18 or so, is wrong: it causes
727 ;; a warning at MACROEXPAND time, when instead the warning should
728 ;; occur not just because the code was constructed, but because it
729 ;; is actually compiled or loaded.
733 (setf (dsd-default slot) default))
735 (setf (dsd-type slot)
736 (if (eq (dsd-type slot) t)
738 `(and ,(dsd-type slot) ,type))))
741 (setf (dsd-read-only slot) t)
742 (when (dsd-read-only slot)
743 (error "~@<The slot ~S is :READ-ONLY in superclass, and so must ~
744 be :READ-ONLY in subclass.~:@>"
748 ;;; When a value of type TYPE is stored in a structure, should it be
749 ;;; stored in a raw slot? Return the matching RAW-SLOT-DATA structure
750 ;; if TYPE should be stored in a raw slot, or NIL if not.
751 (defun structure-raw-slot-data (type)
752 (multiple-value-bind (fixnum? fixnum-certain?)
753 (sb!xc:subtypep type 'fixnum)
754 ;; (The extra test for FIXNUM-CERTAIN? here is intended for
755 ;; bootstrapping the system. In particular, in sbcl-0.6.2, we set up
756 ;; LAYOUT before FIXNUM is defined, and so could bogusly end up
757 ;; putting INDEX-typed values into raw slots if we didn't test
759 (if (or fixnum? (not fixnum-certain?))
761 (dolist (data *raw-slot-data-list*)
762 (when (sb!xc:subtypep type (raw-slot-data-raw-type data))
765 ;;; Allocate storage for a DSD in DD. This is where we decide whether
766 ;;; a slot is raw or not. Raw objects are aligned on the unit of their size.
767 (defun allocate-1-slot (dd dsd)
769 (if (eq (dd-type dd) 'structure)
770 (structure-raw-slot-data (dsd-type dsd))
774 (setf (dsd-index dsd) (dd-length dd))
775 (incf (dd-length dd)))
777 (let* ((words (raw-slot-data-n-words rsd))
778 (alignment (raw-slot-data-alignment rsd))
779 (off (rem (dd-raw-length dd) alignment)))
781 (incf (dd-raw-length dd) (- alignment off)))
782 (setf (dsd-raw-type dsd) (raw-slot-data-raw-type rsd))
783 (setf (dsd-index dsd) (dd-raw-length dd))
784 (incf (dd-raw-length dd) words)))))
787 (defun typed-structure-info-or-lose (name)
788 (or (info :typed-structure :info name)
789 (error ":TYPE'd DEFSTRUCT ~S not found for inclusion." name)))
791 ;;; Process any included slots pretty much like they were specified.
792 ;;; Also inherit various other attributes.
793 (defun frob-dd-inclusion-stuff (dd)
794 (destructuring-bind (included-name &rest modified-slots) (dd-include dd)
795 (let* ((type (dd-type dd))
798 (layout-info (compiler-layout-or-lose included-name))
799 (typed-structure-info-or-lose included-name))))
801 ;; checks on legality
802 (unless (and (eq type (dd-type included-structure))
803 (type= (specifier-type (dd-element-type included-structure))
804 (specifier-type (dd-element-type dd))))
805 (error ":TYPE option mismatch between structures ~S and ~S"
806 (dd-name dd) included-name))
807 (let ((included-classoid (find-classoid included-name nil)))
808 (when included-classoid
809 ;; It's not particularly well-defined to :INCLUDE any of the
810 ;; CMU CL INSTANCE weirdosities like CONDITION or
811 ;; GENERIC-FUNCTION, and it's certainly not ANSI-compliant.
812 (let* ((included-layout (classoid-layout included-classoid))
813 (included-dd (layout-info included-layout)))
814 (when (and (dd-alternate-metaclass included-dd)
815 ;; As of sbcl-0.pre7.73, anyway, STRUCTURE-OBJECT
816 ;; is represented with an ALTERNATE-METACLASS. But
817 ;; it's specifically OK to :INCLUDE (and PCL does)
818 ;; so in this one case, it's OK to include
819 ;; something with :ALTERNATE-METACLASS after all.
820 (not (eql included-name 'structure-object)))
821 (error "can't :INCLUDE class ~S (has alternate metaclass)"
824 (incf (dd-length dd) (dd-length included-structure))
825 (when (dd-class-p dd)
826 (let ((mc (rest (dd-alternate-metaclass included-structure))))
827 (when (and mc (not (dd-alternate-metaclass dd)))
828 (setf (dd-alternate-metaclass dd)
829 (cons included-name mc))))
830 (when (eq (dd-pure dd) :unspecified)
831 (setf (dd-pure dd) (dd-pure included-structure)))
832 (setf (dd-raw-length dd) (dd-raw-length included-structure)))
834 (setf (dd-inherited-accessor-alist dd)
835 (dd-inherited-accessor-alist included-structure))
836 (dolist (included-slot (dd-slots included-structure))
837 (let* ((included-name (dsd-name included-slot))
838 (modified (or (find included-name modified-slots
839 :key (lambda (x) (if (atom x) x (car x)))
842 ;; We stash away an alist of accessors to parents' slots
843 ;; that have already been created to avoid conflicts later
844 ;; so that structures with :INCLUDE and :CONC-NAME (and
845 ;; other edge cases) can work as specified.
846 (when (dsd-accessor-name included-slot)
847 ;; the "oldest" (i.e. highest up the tree of inheritance)
848 ;; will prevail, so don't push new ones on if they
850 (pushnew (cons (dsd-accessor-name included-slot)
851 (dsd-index included-slot))
852 (dd-inherited-accessor-alist dd)
853 :test #'eq :key #'car))
854 (let ((new-slot (parse-1-dsd dd
856 (copy-structure included-slot))))
857 (when (and (neq (dsd-type new-slot) (dsd-type included-slot))
858 (not (sb!xc:subtypep (dsd-type included-slot)
859 (dsd-type new-slot)))
860 (dsd-safe-p included-slot))
861 (setf (dsd-safe-p new-slot) nil)
865 ;;;; various helper functions for setting up DEFSTRUCTs
867 ;;; This function is called at macroexpand time to compute the INHERITS
868 ;;; vector for a structure type definition.
869 (defun inherits-for-structure (info)
870 (declare (type defstruct-description info))
871 (let* ((include (dd-include info))
872 (superclass-opt (dd-alternate-metaclass info))
875 (compiler-layout-or-lose (first include))
876 (classoid-layout (find-classoid
877 (or (first superclass-opt)
878 'structure-object))))))
881 (concatenate 'simple-vector
882 (layout-inherits super)
883 (vector super (classoid-layout (find-classoid 'stream)))))
885 (concatenate 'simple-vector
886 (layout-inherits super)
888 (classoid-layout (find-classoid 'file-stream)))))
889 ((sb!impl::string-input-stream
890 sb!impl::string-output-stream
891 sb!impl::fill-pointer-output-stream)
892 (concatenate 'simple-vector
893 (layout-inherits super)
895 (classoid-layout (find-classoid 'string-stream)))))
896 (t (concatenate 'simple-vector
897 (layout-inherits super)
900 ;;; Do miscellaneous (LOAD EVAL) time actions for the structure
901 ;;; described by DD. Create the class and LAYOUT, checking for
902 ;;; incompatible redefinition. Define those functions which are
903 ;;; sufficiently stereotyped that we can implement them as standard
905 (defun %defstruct (dd inherits source-location)
906 (declare (type defstruct-description dd))
908 ;; We set up LAYOUTs even in the cross-compilation host.
909 (multiple-value-bind (classoid layout old-layout)
910 (ensure-structure-class dd inherits "current" "new")
911 (cond ((not old-layout)
912 (unless (eq (classoid-layout classoid) layout)
913 (register-layout layout)))
915 (%redefine-defstruct classoid old-layout layout)
916 (let ((old-dd (layout-info old-layout)))
917 (when (defstruct-description-p old-dd)
918 (dolist (slot (dd-slots old-dd))
919 (fmakunbound (dsd-accessor-name slot))
920 (unless (dsd-read-only slot)
921 (fmakunbound `(setf ,(dsd-accessor-name slot)))))))
922 (setq layout (classoid-layout classoid))))
923 (setf (find-classoid (dd-name dd)) classoid)
925 (sb!c:with-source-location (source-location)
926 (setf (layout-source-location layout) source-location))
928 ;; Various other operations only make sense on the target SBCL.
930 (%target-defstruct dd layout))
934 ;;; Return a form describing the writable place used for this slot
935 ;;; in the instance named INSTANCE-NAME.
936 (defun %accessor-place-form (dd dsd instance-name)
937 (let (;; the operator that we'll use to access a typed slot
938 (ref (ecase (dd-type dd)
939 (structure '%instance-ref)
940 (list 'nth-but-with-sane-arg-order)
942 (raw-type (dsd-raw-type dsd)))
943 (if (eq raw-type t) ; if not raw slot
944 `(,ref ,instance-name ,(dsd-index dsd))
945 (let* ((raw-slot-data (find raw-type *raw-slot-data-list*
946 :key #'raw-slot-data-raw-type
948 (raw-slot-accessor (raw-slot-data-accessor-name raw-slot-data)))
949 `(,raw-slot-accessor ,instance-name ,(dsd-index dsd))))))
951 ;;; Return source transforms for the reader and writer functions of
952 ;;; the slot described by DSD. They should be inline expanded, but
953 ;;; source transforms work faster.
954 (defun slot-accessor-transforms (dd dsd)
955 (let ((accessor-place-form (%accessor-place-form dd dsd
956 `(the ,(dd-name dd) instance)))
957 (dsd-type (dsd-type dsd))
958 (value-the (if (dsd-safe-p dsd) 'truly-the 'the)))
959 (values (sb!c:source-transform-lambda (instance)
960 `(,value-the ,dsd-type ,(subst instance 'instance
961 accessor-place-form)))
962 (sb!c:source-transform-lambda (new-value instance)
963 (destructuring-bind (accessor-name &rest accessor-args)
965 (once-only ((new-value new-value)
967 `(,(info :setf :inverse accessor-name)
968 ,@(subst instance 'instance accessor-args)
969 (the ,dsd-type ,new-value))))))))
971 ;;; Return a LAMBDA form which can be used to set a slot.
972 (defun slot-setter-lambda-form (dd dsd)
973 ;; KLUDGE: Evaluating the results of SLOT-ACCESSOR-TRANSFORMS needs
975 (let ((sb!c:*lexenv* (if (boundp 'sb!c:*lexenv*)
977 (sb!c::make-null-lexenv))))
978 `(lambda (new-value instance)
979 ,(funcall (nth-value 1 (slot-accessor-transforms dd dsd))
980 '(dummy new-value instance)))))
982 ;;; core compile-time setup of any class with a LAYOUT, used even by
983 ;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS weirdosities
984 (defun %compiler-set-up-layout (dd
986 ;; Several special cases
987 ;; (STRUCTURE-OBJECT itself, and
988 ;; structures with alternate
989 ;; metaclasses) call this function
990 ;; directly, and they're all at the
991 ;; base of the instance class
992 ;; structure, so this is a handy
993 ;; default. (But note
994 ;; FUNCALLABLE-STRUCTUREs need
996 (inherits (vector (find-layout t))))
998 (multiple-value-bind (classoid layout old-layout)
999 (multiple-value-bind (clayout clayout-p)
1000 (info :type :compiler-layout (dd-name dd))
1001 (ensure-structure-class dd
1004 "The most recently compiled"
1006 "the most recently loaded"
1007 :compiler-layout clayout))
1010 ;; Blow away all the compiler info for the structure
1011 ;; CLASS. Iterate over this type, clearing the compiler
1012 ;; structure type info, and undefining all the
1013 ;; associated functions. FIXME: maybe rename
1014 ;; UNDEFINE-FUN-NAME to UNDECLARE-FUNCTION-NAME?
1015 ((undeclare-structure (classoid subclasses-p)
1016 (let ((info (layout-info (classoid-layout classoid))))
1017 (when (defstruct-description-p info)
1018 (let ((type (dd-name info)))
1019 (remhash type *typecheckfuns*)
1020 (setf (info :type :compiler-layout type) nil)
1021 (undefine-fun-name (dd-copier-name info))
1022 (undefine-fun-name (dd-predicate-name info))
1023 (dolist (slot (dd-slots info))
1024 (let ((fun (dsd-accessor-name slot)))
1025 (unless (accessor-inherited-data fun info)
1026 (undefine-fun-name fun)
1027 (unless (dsd-read-only slot)
1028 (undefine-fun-name `(setf ,fun)))))))
1029 ;; Clear out the SPECIFIER-TYPE cache so that subsequent
1030 ;; references are unknown types.
1031 (values-specifier-type-cache-clear)))
1034 (dohash ((classoid layout)
1035 (classoid-subclasses classoid)
1037 (declare (ignore layout))
1038 (undeclare-structure classoid nil)
1039 (subs (classoid-proper-name classoid)))
1040 ;; Is it really necessary to warn about
1041 ;; undeclaring functions for subclasses?
1043 (warn "undeclaring functions for old subclasses ~
1045 (classoid-name classoid)
1047 (undeclare-structure (layout-classoid old-layout)
1048 (and (classoid-subclasses classoid)
1049 (not (eq layout old-layout))))
1050 (setf (layout-invalid layout) nil)
1051 ;; FIXME: it might be polite to hold onto old-layout and
1052 ;; restore it at the end of the file. -- RMK 2008-09-19
1053 ;; (International Talk Like a Pirate Day).
1054 (warn "~@<Clobbering the compiler's idea of the layout of ~A.~:@>"
1057 (unless (eq (classoid-layout classoid) layout)
1058 (register-layout layout :invalidate nil))
1059 (setf (find-classoid (dd-name dd)) classoid)))
1061 ;; At this point the class should be set up in the INFO database.
1062 ;; But the logic that enforces this is a little tangled and
1063 ;; scattered, so it's not obvious, so let's check.
1064 (aver (find-classoid (dd-name dd) nil))
1066 (setf (info :type :compiler-layout (dd-name dd)) layout))
1070 ;;; Do (COMPILE LOAD EVAL)-time actions for the normal (not
1071 ;;; ALTERNATE-LAYOUT) DEFSTRUCT described by DD.
1072 (defun %compiler-defstruct (dd inherits)
1073 (declare (type defstruct-description dd))
1075 (%compiler-set-up-layout dd inherits)
1077 (let* ((dtype (dd-declarable-type dd)))
1079 (let ((copier-name (dd-copier-name dd)))
1081 (sb!xc:proclaim `(ftype (sfunction (,dtype) ,dtype) ,copier-name))))
1083 (let ((predicate-name (dd-predicate-name dd)))
1084 (when predicate-name
1085 (sb!xc:proclaim `(ftype (sfunction (t) boolean) ,predicate-name))
1086 ;; Provide inline expansion (or not).
1088 ((structure funcallable-structure)
1089 ;; Let the predicate be inlined.
1090 (setf (info :function :inline-expansion-designator predicate-name)
1093 ;; This dead simple definition works because the
1094 ;; type system knows how to generate inline type
1095 ;; tests for instances.
1096 (typep x ',(dd-name dd))))
1097 (info :function :inlinep predicate-name)
1100 ;; Just punt. We could provide inline expansions for :TYPE
1101 ;; LIST and :TYPE VECTOR predicates too, but it'd be a
1102 ;; little messier and we don't bother. (Does anyway use
1103 ;; typed DEFSTRUCTs at all, let alone for high
1107 (dolist (dsd (dd-slots dd))
1108 (let* ((accessor-name (dsd-accessor-name dsd))
1109 (dsd-type (dsd-type dsd)))
1111 (setf (info :function :structure-accessor accessor-name) dd)
1112 (let ((inherited (accessor-inherited-data accessor-name dd)))
1115 (multiple-value-bind (reader-designator writer-designator)
1116 (slot-accessor-transforms dd dsd)
1117 (sb!xc:proclaim `(ftype (sfunction (,dtype) ,dsd-type)
1119 (setf (info :function :source-transform accessor-name)
1121 (unless (dsd-read-only dsd)
1122 (let ((setf-accessor-name `(setf ,accessor-name)))
1124 `(ftype (sfunction (,dsd-type ,dtype) ,dsd-type)
1125 ,setf-accessor-name))
1126 (setf (info :function :source-transform setf-accessor-name)
1127 writer-designator)))))
1128 ((not (= (cdr inherited) (dsd-index dsd)))
1129 (style-warn "~@<Non-overwritten accessor ~S does not access ~
1130 slot with name ~S (accessing an inherited slot ~
1133 (dsd-name dsd)))))))))
1136 ;;;; redefinition stuff
1138 ;;; Compare the slots of OLD and NEW, returning 3 lists of slot names:
1139 ;;; 1. Slots which have moved,
1140 ;;; 2. Slots whose type has changed,
1141 ;;; 3. Deleted slots.
1142 (defun compare-slots (old new)
1143 (let* ((oslots (dd-slots old))
1144 (nslots (dd-slots new))
1145 (onames (mapcar #'dsd-name oslots))
1146 (nnames (mapcar #'dsd-name nslots)))
1149 (dolist (name (intersection onames nnames))
1150 (let ((os (find name oslots :key #'dsd-name :test #'string=))
1151 (ns (find name nslots :key #'dsd-name :test #'string=)))
1152 (unless (sb!xc:subtypep (dsd-type ns) (dsd-type os))
1154 (unless (and (= (dsd-index os) (dsd-index ns))
1155 (eq (dsd-raw-type os) (dsd-raw-type ns)))
1159 (set-difference onames nnames :test #'string=)))))
1161 ;;; If we are redefining a structure with different slots than in the
1162 ;;; currently loaded version, give a warning and return true.
1163 (defun redefine-structure-warning (classoid old new)
1164 (declare (type defstruct-description old new)
1165 (type classoid classoid)
1167 (let ((name (dd-name new)))
1168 (multiple-value-bind (moved retyped deleted) (compare-slots old new)
1169 (when (or moved retyped deleted)
1171 "incompatibly redefining slots of structure class ~S~@
1172 Make sure any uses of affected accessors are recompiled:~@
1173 ~@[ These slots were moved to new positions:~% ~S~%~]~
1174 ~@[ These slots have new incompatible types:~% ~S~%~]~
1175 ~@[ These slots were deleted:~% ~S~%~]"
1176 name moved retyped deleted)
1179 ;;; This function is called when we are incompatibly redefining a
1180 ;;; structure CLASS to have the specified NEW-LAYOUT. We signal an
1181 ;;; error with some proceed options and return the layout that should
1183 (defun %redefine-defstruct (classoid old-layout new-layout)
1184 (declare (type classoid classoid)
1185 (type layout old-layout new-layout))
1186 (let ((name (classoid-proper-name classoid)))
1188 (error "~@<attempt to redefine the ~S class ~S incompatibly with the current definition~:@>"
1194 "~@<Use the new definition of ~S, invalidating ~
1195 already-loaded code and instances.~@:>"
1197 (register-layout new-layout))
1198 (recklessly-continue ()
1201 "~@<Use the new definition of ~S as if it were ~
1202 compatible, allowing old accessors to use new ~
1203 instances and allowing new accessors to use old ~
1206 ;; classic CMU CL warning: "Any old ~S instances will be in a bad way.
1207 ;; I hope you know what you're doing..."
1208 (register-layout new-layout
1210 :destruct-layout old-layout))
1212 ;; FIXME: deprecated 2002-10-16, and since it's only interactive
1213 ;; hackery instead of a supported feature, can probably be deleted
1215 :report "(deprecated synonym for RECKLESSLY-CONTINUE)"
1216 (register-layout new-layout
1218 :destruct-layout old-layout))))
1221 (declaim (inline dd-layout-length))
1222 (defun dd-layout-length (dd)
1223 (+ (dd-length dd) (dd-raw-length dd)))
1225 (declaim (ftype (sfunction (defstruct-description) index) dd-instance-length))
1226 (defun dd-instance-length (dd)
1227 ;; Make sure the object ends at a two-word boundary. Note that this does
1228 ;; not affect the amount of memory used, since the allocator would add the
1229 ;; same padding anyway. However, raw slots are indexed from the length of
1230 ;; the object as indicated in the header, so the pad word needs to be
1231 ;; included in that length to guarantee proper alignment of raw double float
1232 ;; slots, necessary for (at least) the SPARC backend.
1233 (let ((layout-length (dd-layout-length dd)))
1234 (declare (index layout-length))
1235 (+ layout-length (mod (1+ layout-length) 2))))
1237 ;;; This is called when we are about to define a structure class. It
1238 ;;; returns a (possibly new) class object and the layout which should
1239 ;;; be used for the new definition (may be the current layout, and
1240 ;;; also might be an uninstalled forward referenced layout.) The third
1241 ;;; value is true if this is an incompatible redefinition, in which
1242 ;;; case it is the old layout.
1243 (defun ensure-structure-class (info inherits old-context new-context
1244 &key compiler-layout)
1245 (multiple-value-bind (class old-layout)
1249 (class 'structure-classoid)
1250 (constructor 'make-structure-classoid))
1251 (dd-alternate-metaclass info)
1252 (declare (ignore name))
1253 (insured-find-classoid (dd-name info)
1254 (if (eq class 'structure-classoid)
1256 (sb!xc:typep x 'structure-classoid))
1258 (sb!xc:typep x (classoid-name (find-classoid class)))))
1259 (fdefinition constructor)))
1260 (setf (classoid-direct-superclasses class)
1261 (case (dd-name info)
1264 sb!impl::string-input-stream sb!impl::string-output-stream
1265 sb!impl::fill-pointer-output-stream)
1266 (list (layout-classoid (svref inherits (1- (length inherits))))
1267 (layout-classoid (svref inherits (- (length inherits) 2)))))
1269 (list (layout-classoid
1270 (svref inherits (1- (length inherits))))))))
1271 (let ((new-layout (make-layout :classoid class
1273 :depthoid (length inherits)
1274 :length (dd-layout-length info)
1275 :n-untagged-slots (dd-raw-length info)
1277 (old-layout (or compiler-layout old-layout)))
1280 (values class new-layout nil))
1281 (;; This clause corresponds to an assertion in REDEFINE-LAYOUT-WARNING
1282 ;; of classic CMU CL. I moved it out to here because it was only
1283 ;; exercised in this code path anyway. -- WHN 19990510
1284 (not (eq (layout-classoid new-layout) (layout-classoid old-layout)))
1285 (error "shouldn't happen: weird state of OLD-LAYOUT?"))
1286 ((not *type-system-initialized*)
1287 (setf (layout-info old-layout) info)
1288 (values class old-layout nil))
1289 ((redefine-layout-warning old-context
1292 (layout-length new-layout)
1293 (layout-inherits new-layout)
1294 (layout-depthoid new-layout)
1295 (layout-n-untagged-slots new-layout))
1296 (values class new-layout old-layout))
1298 (let ((old-info (layout-info old-layout)))
1300 ((or defstruct-description)
1301 (cond ((redefine-structure-warning class old-info info)
1302 (values class new-layout old-layout))
1304 (setf (layout-info old-layout) info)
1305 (values class old-layout nil))))
1307 (setf (layout-info old-layout) info)
1308 (values class old-layout nil))
1310 (error "shouldn't happen! strange thing in LAYOUT-INFO:~% ~S"
1312 (values class new-layout old-layout)))))))))
1314 ;;; Return a list of pairs (name . index). Used for :TYPE'd
1315 ;;; constructors to find all the names that we have to splice in &
1316 ;;; where. Note that these types don't have a layout, so we can't look
1317 ;;; at LAYOUT-INHERITS.
1318 (defun find-name-indices (defstruct)
1321 (do ((info defstruct
1322 (typed-structure-info-or-lose (first (dd-include info)))))
1323 ((not (dd-include info))
1328 (dolist (info infos)
1329 (incf i (or (dd-offset info) 0))
1330 (when (dd-named info)
1331 (res (cons (dd-name info) i)))
1332 (setq i (dd-length info)))))
1336 ;;; These functions are called to actually make a constructor after we
1337 ;;; have processed the arglist. The correct variant (according to the
1338 ;;; DD-TYPE) should be called. The function is defined with the
1339 ;;; specified name and arglist. VARS and TYPES are used for argument
1340 ;;; type declarations. VALUES are the values for the slots (in order.)
1342 ;;; This is split three ways because:
1343 ;;; * LIST & VECTOR structures need "name" symbols stuck in at
1344 ;;; various weird places, whereas STRUCTURE structures have
1346 ;;; * We really want to use LIST to make list structures, instead of
1347 ;;; MAKE-LIST/(SETF ELT). (We can't in general use VECTOR in an
1348 ;;; analogous way, since VECTOR makes a SIMPLE-VECTOR and vector-typed
1349 ;;; structures can have arbitrary subtypes of VECTOR, not necessarily
1351 ;;; * STRUCTURE structures can have raw slots that must also be
1352 ;;; allocated and indirectly referenced.
1353 (defun create-vector-constructor (dd cons-name arglist vars types values)
1354 (let ((temp (gensym))
1355 (etype (dd-element-type dd)))
1356 `(defun ,cons-name ,arglist
1357 (declare ,@(mapcar (lambda (var type) `(type (and ,type ,etype) ,var))
1359 (let ((,temp (make-array ,(dd-length dd)
1360 :element-type ',(dd-element-type dd))))
1361 ,@(mapcar (lambda (x)
1362 `(setf (aref ,temp ,(cdr x)) ',(car x)))
1363 (find-name-indices dd))
1364 ,@(mapcar (lambda (dsd value)
1365 (unless (eq value '.do-not-initialize-slot.)
1366 `(setf (aref ,temp ,(dsd-index dsd)) ,value)))
1367 (dd-slots dd) values)
1369 (defun create-list-constructor (dd cons-name arglist vars types values)
1370 (let ((vals (make-list (dd-length dd) :initial-element nil)))
1371 (dolist (x (find-name-indices dd))
1372 (setf (elt vals (cdr x)) `',(car x)))
1373 (loop for dsd in (dd-slots dd) and val in values do
1374 (setf (elt vals (dsd-index dsd))
1375 (if (eq val '.do-not-initialize-slot.) 0 val)))
1376 `(defun ,cons-name ,arglist
1377 (declare ,@(mapcar (lambda (var type) `(type ,type ,var)) vars types))
1379 (defun create-structure-constructor (dd cons-name arglist vars types values)
1380 ;; The difference between the two implementations here is that on all
1381 ;; platforms we don't have the appropriate RAW-INSTANCE-INIT VOPS, which
1382 ;; must be able to deal with immediate values as well -- unlike
1383 ;; RAW-INSTANCE-SET VOPs, which never end up seeing immediate values. With
1384 ;; some additional cleverness we might manage without them and just a single
1385 ;; implementation here, though -- figure out a way to ensure that on those
1386 ;; platforms we always still get a non-immediate TN in every case...
1388 ;; Until someone does that, this means that instances with raw slots can be
1389 ;; DX allocated only on platforms with those additional VOPs.
1390 #!+raw-instance-init-vops
1391 (let* ((slot-values nil)
1393 (mapcan (lambda (dsd value)
1394 (unless (eq value '.do-not-initialize-slot.)
1395 (push value slot-values)
1396 (list (list* :slot (dsd-raw-type dsd) (dsd-index dsd)))))
1399 `(defun ,cons-name ,arglist
1400 (declare ,@(mapcar (lambda (var type) `(type ,type ,var)) vars types))
1401 (%make-structure-instance-macro ,dd ',slot-specs ,@(reverse slot-values))))
1402 #!-raw-instance-init-vops
1403 (let ((instance (gensym "INSTANCE")) slot-values slot-specs raw-slots raw-values)
1404 (mapc (lambda (dsd value)
1405 (unless (eq value '.do-not-initialize-slot.)
1406 (let ((raw-type (dsd-raw-type dsd)))
1407 (cond ((eq t raw-type)
1408 (push value slot-values)
1409 (push (list* :slot raw-type (dsd-index dsd)) slot-specs))
1411 (push value raw-values)
1412 (push dsd raw-slots))))))
1415 `(defun ,cons-name ,arglist
1416 (declare ,@(mapcar (lambda (var type) `(type ,type ,var)) vars types))
1418 `(let ((,instance (%make-structure-instance-macro ,dd ',slot-specs ,@slot-values)))
1419 ,@(mapcar (lambda (dsd value)
1420 ;; (Note that we can't in general use the
1421 ;; ordinary named slot setter function here
1422 ;; because the slot might be :READ-ONLY, so we
1423 ;; whip up new LAMBDA representations of slot
1424 ;; setters for the occasion.)
1425 `(,(slot-setter-lambda-form dd dsd) ,value ,instance))
1429 `(%make-structure-instance-macro ,dd ',slot-specs ,@slot-values)))))
1431 ;;; Create a default (non-BOA) keyword constructor.
1432 (defun create-keyword-constructor (defstruct creator)
1433 (declare (type function creator))
1434 (collect ((arglist (list '&key))
1437 (dolist (slot (dd-slots defstruct))
1438 (let ((dum (gensym))
1439 (name (dsd-name slot)))
1440 (arglist `((,(keywordicate name) ,dum) ,(dsd-default slot)))
1441 (types (dsd-type slot))
1444 defstruct (dd-default-constructor defstruct)
1445 (arglist) (vals) (types) (vals))))
1447 ;;; Given a structure and a BOA constructor spec, call CREATOR with
1448 ;;; the appropriate args to make a constructor.
1449 (defun create-boa-constructor (defstruct boa creator)
1450 (declare (type function creator))
1451 (multiple-value-bind (req opt restp rest keyp keys allowp auxp aux)
1452 (parse-lambda-list (second boa))
1457 (labels ((get-slot (name)
1458 (let ((res (find name (dd-slots defstruct)
1462 (values (dsd-type res) (dsd-default res))
1465 (multiple-value-bind (type default) (get-slot arg)
1466 (arglist `(,arg ,default))
1472 (types (get-slot arg)))
1475 (arglist '&optional)
1479 ;; FIXME: this shares some logic (though not
1480 ;; code) with the &key case below (and it
1481 ;; looks confusing) -- factor out the logic
1482 ;; if possible. - CSR, 2002-04-19
1485 (def (nth-value 1 (get-slot name)))
1486 (supplied-test nil supplied-test-p))
1488 (arglist `(,name ,def ,@(if supplied-test-p `(,supplied-test) nil)))
1490 (types (get-slot name))))
1492 (do-default arg)))))
1495 (arglist '&rest rest)
1503 (destructuring-bind (wot
1506 (supplied-test nil supplied-test-p))
1508 (let ((name (if (consp wot)
1509 (destructuring-bind (key var) wot
1510 (declare (ignore key))
1513 (multiple-value-bind (type slot-def)
1515 (arglist `(,wot ,(if def-p def slot-def)
1516 ,@(if supplied-test-p `(,supplied-test) nil)))
1521 (when allowp (arglist '&allow-other-keys))
1527 (if (proper-list-of-length-p arg 2)
1528 (let ((var (first arg)))
1530 (types (get-slot var)))
1531 (skipped-vars (if (consp arg) (first arg) arg))))))
1533 (funcall creator defstruct (first boa)
1534 (arglist) (vars) (types)
1535 (loop for slot in (dd-slots defstruct)
1536 for name = (dsd-name slot)
1537 collect (cond ((find name (skipped-vars) :test #'string=)
1538 ;; CLHS 3.4.6 Boa Lambda Lists
1539 (setf (dsd-safe-p slot) nil)
1540 '.do-not-initialize-slot.)
1541 ((or (find (dsd-name slot) (vars) :test #'string=)
1542 (let ((type (dsd-type slot)))
1545 `(the ,type ,(dsd-default slot))))))))))))
1547 ;;; Grovel the constructor options, and decide what constructors (if
1549 (defun constructor-definitions (defstruct)
1550 (let ((no-constructors nil)
1553 (creator (ecase (dd-type defstruct)
1554 (structure #'create-structure-constructor)
1555 (vector #'create-vector-constructor)
1556 (list #'create-list-constructor))))
1557 (dolist (constructor (dd-constructors defstruct))
1558 (destructuring-bind (name &optional (boa-ll nil boa-p)) constructor
1559 (declare (ignore boa-ll))
1560 (cond ((not name) (setq no-constructors t))
1561 (boa-p (push constructor boas))
1562 (t (push name defaults)))))
1564 (when no-constructors
1565 (when (or defaults boas)
1566 (error "(:CONSTRUCTOR NIL) combined with other :CONSTRUCTORs"))
1567 (return-from constructor-definitions ()))
1569 (unless (or defaults boas)
1570 (push (symbolicate "MAKE-" (dd-name defstruct)) defaults))
1572 (collect ((res) (names))
1574 (let ((cname (first defaults)))
1575 (setf (dd-default-constructor defstruct) cname)
1576 (res (create-keyword-constructor defstruct creator))
1578 (dolist (other-name (rest defaults))
1579 (res `(setf (fdefinition ',other-name) (fdefinition ',cname)))
1580 (names other-name))))
1583 (res (create-boa-constructor defstruct boa creator))
1584 (names (first boa)))
1586 (res `(declaim (ftype
1588 ,(if (eq (dd-type defstruct) 'structure)
1595 ;;;; instances with ALTERNATE-METACLASS
1597 ;;;; The CMU CL support for structures with ALTERNATE-METACLASS was a
1598 ;;;; fairly general extension embedded in the main DEFSTRUCT code, and
1599 ;;;; the result was an fairly impressive mess as ALTERNATE-METACLASS
1600 ;;;; extension mixed with ANSI CL generality (e.g. :TYPE and :INCLUDE)
1601 ;;;; and CMU CL implementation hairiness (esp. raw slots). This SBCL
1602 ;;;; version is much less ambitious, noticing that ALTERNATE-METACLASS
1603 ;;;; is only used to implement CONDITION, STANDARD-INSTANCE, and
1604 ;;;; GENERIC-FUNCTION, and defining a simple specialized
1605 ;;;; separate-from-DEFSTRUCT macro to provide only enough
1606 ;;;; functionality to support those.
1608 ;;;; KLUDGE: The defining macro here is so specialized that it's ugly
1609 ;;;; in its own way. It also violates once-and-only-once by knowing
1610 ;;;; much about structures and layouts that is already known by the
1611 ;;;; main DEFSTRUCT macro. Hopefully it will go away presently
1612 ;;;; (perhaps when CL:CLASS and SB-PCL:CLASS meet) as per FIXME below.
1613 ;;;; -- WHN 2001-10-28
1615 ;;;; FIXME: There seems to be no good reason to shoehorn CONDITION,
1616 ;;;; STANDARD-INSTANCE, and GENERIC-FUNCTION into mutated structures
1617 ;;;; instead of just implementing them as primitive objects. (This
1618 ;;;; reduced-functionality macro seems pretty close to the
1619 ;;;; functionality of DEFINE-PRIMITIVE-OBJECT..)
1621 (defun make-dd-with-alternate-metaclass (&key (class-name (missing-arg))
1622 (superclass-name (missing-arg))
1623 (metaclass-name (missing-arg))
1624 (dd-type (missing-arg))
1625 metaclass-constructor
1627 (let* ((dd (make-defstruct-description class-name))
1628 (conc-name (concatenate 'string (symbol-name class-name) "-"))
1629 (dd-slots (let ((reversed-result nil)
1630 ;; The index starts at 1 for ordinary named
1631 ;; slots because slot 0 is magical, used for
1632 ;; the LAYOUT in CONDITIONs and
1633 ;; FUNCALLABLE-INSTANCEs. (This is the same
1634 ;; in ordinary structures too: see (INCF
1636 ;; PARSE-DEFSTRUCT-NAME-AND-OPTIONS).
1638 (dolist (slot-name slot-names)
1639 (push (make-defstruct-slot-description
1642 :accessor-name (symbolicate conc-name slot-name))
1645 (nreverse reversed-result))))
1647 ;; We don't support inheritance of alternate metaclass stuff,
1648 ;; and it's not a general-purpose facility, so sanity check our
1651 (aver (eq superclass-name 't)))
1652 (funcallable-structure
1653 (aver (eq superclass-name 'function)))
1654 (t (bug "Unknown DD-TYPE in ALTERNATE-METACLASS: ~S" dd-type)))
1655 (setf (dd-alternate-metaclass dd) (list superclass-name
1657 metaclass-constructor)
1658 (dd-slots dd) dd-slots
1659 (dd-length dd) (1+ (length slot-names))
1660 (dd-type dd) dd-type)
1663 ;;; make !DEFSTRUCT-WITH-ALTERNATE-METACLASS compilable by the host
1664 ;;; lisp, installing the information we need to reason about the
1665 ;;; structures (layouts and classoids).
1667 ;;; FIXME: we should share the parsing and the DD construction between
1668 ;;; this and the cross-compiler version, but my brain was too small to
1669 ;;; get that right. -- CSR, 2006-09-14
1671 (defmacro !defstruct-with-alternate-metaclass
1673 (slot-names (missing-arg))
1674 (boa-constructor (missing-arg))
1675 (superclass-name (missing-arg))
1676 (metaclass-name (missing-arg))
1677 (metaclass-constructor (missing-arg))
1678 (dd-type (missing-arg))
1680 (runtime-type-checks-p t))
1682 (declare (type (and list (not null)) slot-names))
1683 (declare (type (and symbol (not null))
1687 metaclass-constructor))
1688 (declare (type symbol predicate))
1689 (declare (type (member structure funcallable-structure) dd-type))
1690 (declare (ignore boa-constructor predicate runtime-type-checks-p))
1692 (let* ((dd (make-dd-with-alternate-metaclass
1693 :class-name class-name
1694 :slot-names slot-names
1695 :superclass-name superclass-name
1696 :metaclass-name metaclass-name
1697 :metaclass-constructor metaclass-constructor
1701 (eval-when (:compile-toplevel :load-toplevel :execute)
1702 (%compiler-set-up-layout ',dd ',(inherits-for-structure dd))))))
1704 (sb!xc:defmacro !defstruct-with-alternate-metaclass
1706 (slot-names (missing-arg))
1707 (boa-constructor (missing-arg))
1708 (superclass-name (missing-arg))
1709 (metaclass-name (missing-arg))
1710 (metaclass-constructor (missing-arg))
1711 (dd-type (missing-arg))
1713 (runtime-type-checks-p t))
1715 (declare (type (and list (not null)) slot-names))
1716 (declare (type (and symbol (not null))
1720 metaclass-constructor))
1721 (declare (type symbol predicate))
1722 (declare (type (member structure funcallable-structure) dd-type))
1724 (let* ((dd (make-dd-with-alternate-metaclass
1725 :class-name class-name
1726 :slot-names slot-names
1727 :superclass-name superclass-name
1728 :metaclass-name metaclass-name
1729 :metaclass-constructor metaclass-constructor
1731 (dd-slots (dd-slots dd))
1732 (dd-length (1+ (length slot-names)))
1733 (object-gensym (gensym "OBJECT"))
1734 (new-value-gensym (gensym "NEW-VALUE-"))
1735 (delayed-layout-form `(%delayed-get-compiler-layout ,class-name)))
1736 (multiple-value-bind (raw-maker-form raw-reffer-operator)
1739 (values `(%make-structure-instance-macro ,dd nil)
1741 (funcallable-structure
1742 (values `(let ((,object-gensym
1743 (%make-funcallable-instance ,dd-length)))
1744 (setf (%funcallable-instance-layout ,object-gensym)
1745 ,delayed-layout-form)
1747 '%funcallable-instance-info)))
1750 (eval-when (:compile-toplevel :load-toplevel :execute)
1751 (%compiler-set-up-layout ',dd ',(inherits-for-structure dd)))
1753 ;; slot readers and writers
1754 (declaim (inline ,@(mapcar #'dsd-accessor-name dd-slots)))
1755 ,@(mapcar (lambda (dsd)
1756 `(defun ,(dsd-accessor-name dsd) (,object-gensym)
1757 ,@(when runtime-type-checks-p
1758 `((declare (type ,class-name ,object-gensym))))
1759 (,raw-reffer-operator ,object-gensym
1762 (declaim (inline ,@(mapcar (lambda (dsd)
1763 `(setf ,(dsd-accessor-name dsd)))
1765 ,@(mapcar (lambda (dsd)
1766 `(defun (setf ,(dsd-accessor-name dsd)) (,new-value-gensym
1768 ,@(when runtime-type-checks-p
1769 `((declare (type ,class-name ,object-gensym))))
1770 (setf (,raw-reffer-operator ,object-gensym
1772 ,new-value-gensym)))
1776 (defun ,boa-constructor ,slot-names
1777 (let ((,object-gensym ,raw-maker-form))
1778 ,@(mapcar (lambda (slot-name)
1779 (let ((dsd (find (symbol-name slot-name) dd-slots
1781 (symbol-name (dsd-name x)))
1783 ;; KLUDGE: bug 117 bogowarning. Neither
1784 ;; DECLAREing the type nor TRULY-THE cut
1785 ;; the mustard -- it still gives warnings.
1786 (enforce-type dsd defstruct-slot-description)
1787 `(setf (,(dsd-accessor-name dsd) ,object-gensym)
1794 ;; Just delegate to the compiler's type optimization
1795 ;; code, which knows how to generate inline type tests
1796 ;; for the whole CMU CL INSTANCE menagerie.
1797 `(defun ,predicate (,object-gensym)
1798 (typep ,object-gensym ',class-name)))))))
1800 ;;;; finalizing bootstrapping
1802 ;;; Set up DD and LAYOUT for STRUCTURE-OBJECT class itself.
1804 ;;; Ordinary structure classes effectively :INCLUDE STRUCTURE-OBJECT
1805 ;;; when they have no explicit :INCLUDEs, so (1) it needs to be set up
1806 ;;; before we can define ordinary structure classes, and (2) it's
1807 ;;; special enough (and simple enough) that we just build it by hand
1808 ;;; instead of trying to generalize the ordinary DEFSTRUCT code.
1809 (defun !set-up-structure-object-class ()
1810 (let ((dd (make-defstruct-description 'structure-object)))
1812 ;; Note: This has an ALTERNATE-METACLASS only because of blind
1813 ;; clueless imitation of the CMU CL code -- dunno if or why it's
1815 (dd-alternate-metaclass dd) '(t)
1818 (dd-type dd) 'structure)
1819 (%compiler-set-up-layout dd)))
1820 (!set-up-structure-object-class)
1822 ;;; early structure predeclarations: Set up DD and LAYOUT for ordinary
1823 ;;; (non-ALTERNATE-METACLASS) structures which are needed early.
1825 '#.(sb-cold:read-from-file
1826 "src/code/early-defstruct-args.lisp-expr"))
1827 (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
1830 (inherits (inherits-for-structure dd)))
1831 (%compiler-defstruct dd inherits)))
1833 ;;; finding these beasts
1834 (defun find-defstruct-description (name &optional (errorp t))
1835 (let ((info (layout-info (classoid-layout (find-classoid name errorp)))))
1836 (if (defstruct-description-p info)
1839 (error "No DEFSTRUCT-DESCRIPTION for ~S." name)))))
1841 (/show0 "code/defstruct.lisp end of file")