Declare EXPLICIT-CHECK on CONCATENATE, MAKE-STRING, SET-PPRINT-DISPATCH.
[sbcl.git] / src / code / defstruct.lisp
blob18323416572c021a8145be9ac1ed4272ce213dd9
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
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.
13 (in-package "SB!KERNEL")
15 (/show0 "code/defstruct.lisp 15")
17 ;;;; getting LAYOUTs
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))
28 (sb!int:check-deprecated-type name)
29 res))))
31 (defun compiler-layout-ready-p (name)
32 (let ((layout (info :type :compiler-layout name)))
33 (and layout (typep (layout-info layout) 'defstruct-description))))
35 (sb!xc:defmacro %make-structure-instance-macro (dd slot-specs &rest slot-vars)
36 (if (compiler-layout-ready-p (dd-name dd))
37 `(truly-the ,(dd-name dd)
38 (%make-structure-instance ,dd ,slot-specs ,@slot-vars))
39 ;; Non-toplevel defstructs don't have a layout at compile time,
40 ;; so we need to construct the actual function at runtime -- but
41 ;; we cache it at the call site, so that we don't perform quite
42 ;; so horribly.
43 `(let* ((cell (load-time-value (list nil)))
44 (fun (car cell)))
45 (if (functionp fun)
46 (funcall fun ,@slot-vars)
47 (funcall (setf (car cell)
48 (%make-structure-instance-allocator ,dd ,slot-specs))
49 ,@slot-vars)))))
51 (declaim (ftype (sfunction (defstruct-description list) function)
52 %make-structure-instance-allocator))
53 (defun %make-structure-instance-allocator (dd slot-specs)
54 (let ((vars (make-gensym-list (length slot-specs))))
55 (values (compile nil
56 `(lambda (,@vars)
57 (%make-structure-instance-macro ,dd ',slot-specs ,@vars))))))
59 (defun %make-funcallable-structure-instance-allocator (dd slot-specs)
60 (when slot-specs
61 (bug "funcallable-structure-instance allocation with slots unimplemented"))
62 (let ((name (dd-name dd))
63 (length (dd-length dd))
64 (nobject (gensym "OBJECT")))
65 (values
66 (compile nil `(lambda ()
67 (let ((,nobject (%make-funcallable-instance ,length)))
68 (setf (%funcallable-instance-layout ,nobject)
69 (%delayed-get-compiler-layout ,name))
70 ,nobject))))))
72 ;;; Delay looking for compiler-layout until the constructor is being
73 ;;; compiled, since it doesn't exist until after the EVAL-WHEN
74 ;;; (COMPILE) stuff is compiled. (Or, in the oddball case when
75 ;;; DEFSTRUCT is executing in a non-toplevel context, the
76 ;;; compiler-layout still doesn't exist at compilation time, and we
77 ;;; delay still further.)
78 (sb!xc:defmacro %delayed-get-compiler-layout (name)
79 (let ((layout (info :type :compiler-layout name)))
80 (cond (layout
81 ;; ordinary case: When the DEFSTRUCT is at top level,
82 ;; then EVAL-WHEN (COMPILE) stuff will have set up the
83 ;; layout for us to use.
84 (unless (typep (layout-info layout) 'defstruct-description)
85 (error "Class is not a structure class: ~S" name))
86 `,layout)
88 ;; KLUDGE: In the case that DEFSTRUCT is not at top-level
89 ;; the layout doesn't exist at compile time. In that case
90 ;; we laboriously look it up at run time. This code will
91 ;; run on every constructor call and will likely be quite
92 ;; slow, so if anyone cares about performance of
93 ;; non-toplevel DEFSTRUCTs, it should be rewritten to be
94 ;; cleverer. -- WHN 2002-10-23
95 (sb!c:compiler-notify
96 "implementation limitation: ~
97 Non-toplevel DEFSTRUCT constructors are slow.")
98 (with-unique-names (layout)
99 `(let ((,layout (info :type :compiler-layout ',name)))
100 (unless (typep (layout-info ,layout) 'defstruct-description)
101 (error "Class is not a structure class: ~S" ',name))
102 ,layout))))))
104 ;;; re. %DELAYED-GET-COMPILER-LAYOUT and COMPILE-TIME-FIND-LAYOUT, above..
106 ;;; FIXME: Perhaps both should be defined with DEFMACRO-MUNDANELY?
107 ;;; FIXME: Do we really need both? If so, their names and implementations
108 ;;; should probably be tweaked to be more parallel.
110 ;;;; DEFSTRUCT-DESCRIPTION
112 ;;; The DEFSTRUCT-DESCRIPTION structure holds compile-time information
113 ;;; about a structure type.
114 ;;; Its definition occurs in 'early-classoid.lisp'
115 (def!method print-object ((x defstruct-description) stream)
116 (print-unreadable-object (x stream :type t :identity t)
117 (prin1 (dd-name x) stream)))
119 ;;; Does DD describe a structure with a class?
120 (defun dd-class-p (dd)
121 (if (member (dd-type dd) '(structure funcallable-structure)) t nil))
123 (defun dd-layout-or-lose (dd)
124 (compiler-layout-or-lose (dd-name dd)))
126 ;;;; DEFSTRUCT-SLOT-DESCRIPTION
128 ;;; A DEFSTRUCT-SLOT-DESCRIPTION holds compile-time information about
129 ;;; a structure slot.
130 (def!struct (defstruct-slot-description
131 (:make-load-form-fun just-dump-it-normally)
132 (:conc-name dsd-)
133 (:copier nil)
134 #-sb-xc-host (:pure t))
135 ;; name of slot
136 name
137 ;; its position in the implementation sequence
138 (index (missing-arg) :type fixnum)
139 ;; the name of the accessor function
141 ;; (CMU CL had extra complexity here ("..or NIL if this accessor has
142 ;; the same name as an inherited accessor (which we don't want to
143 ;; shadow)") but that behavior doesn't seem to be specified by (or
144 ;; even particularly consistent with) ANSI, so it's gone in SBCL.)
145 (accessor-name nil :type symbol)
146 default ; default value expression
147 (type t) ; declared type specifier
148 (safe-p t :type boolean) ; whether the slot is known to be
149 ; always of the specified type
150 ;; If this object does not describe a raw slot, this value is T.
152 ;; If this object describes a raw slot, this value is the type of the
153 ;; value that the raw slot holds.
154 ;; Note: if there were more than about 5 raw types - and there aren't -
155 ;; this could be made more efficient by storing either a raw-type-id
156 ;; as an integer index to a vector of the raw types (presently a list,
157 ;; but easily a vector), or actually just the RSD object (raw-slot-data).
158 ;; Doing so would avoid some frequent re-scanning of the RSD list.
159 (raw-type t :type (member t single-float double-float
160 #!+long-float long-float
161 complex-single-float complex-double-float
162 #!+long-float complex-long-float
163 sb!vm:word))
164 (read-only nil :type (member t nil)))
165 #!-sb-fluid (declaim (freeze-type defstruct-slot-description))
166 (def!method print-object ((x defstruct-slot-description) stream)
167 (print-unreadable-object (x stream :type t)
168 (prin1 (dsd-name x) stream)))
170 ;;;; typed (non-class) structures
172 ;;; Return a type specifier we can use for testing :TYPE'd structures.
173 (defun dd-lisp-type (defstruct)
174 (ecase (dd-type defstruct)
175 (list 'list)
176 (vector `(simple-array ,(dd-element-type defstruct) (*)))))
178 ;;;; shared machinery for inline and out-of-line slot accessor functions
180 ;;; Classic comment preserved for entertainment value:
182 ;;; "A lie can travel halfway round the world while the truth is
183 ;;; putting on its shoes." -- Mark Twain
185 ;;;; the legendary DEFSTRUCT macro itself (both CL:DEFSTRUCT and its
186 ;;;; close personal friend SB!XC:DEFSTRUCT)
188 (sb!xc:defmacro delay-defstruct-functions (name forms)
189 ;; KLUDGE: If DEFSTRUCT is not at the top-level,
190 ;; (typep x 'name) and similar forms can't get optimized
191 ;; and produce style-warnings for unknown types.
192 (if (compiler-layout-ready-p name)
193 forms
194 `(eval ',forms)))
196 (defun %defstruct-package-locks (dd)
197 (let ((name (dd-name dd)))
198 #+sb-xc-host (declare (ignore name))
199 (with-single-package-locked-error
200 (:symbol name "defining ~S as a structure"))
201 (awhen (dd-predicate-name dd)
202 (with-single-package-locked-error
203 (:symbol it "defining ~s as a predicate for ~s structure" name)))
204 (awhen (dd-copier-name dd)
205 (with-single-package-locked-error
206 (:symbol it "defining ~s as a copier for ~s structure" name)))
207 (dolist (const (dd-constructors dd))
208 (awhen (car const)
209 (with-single-package-locked-error
210 (:symbol it "defining ~s as a constructor for ~s structure" name))))
211 (dolist (dsd (dd-slots dd))
212 (awhen (dsd-accessor-name dsd)
213 (with-single-package-locked-error
214 (:symbol it "defining ~s as an accessor for ~s structure" name))))))
216 ;;; shared logic for host macroexpansion for SB!XC:DEFSTRUCT and
217 ;;; cross-compiler macroexpansion for CL:DEFSTRUCT
218 (defun %expander-for-defstruct (name-and-options slot-descriptions
219 expanding-into-code-for)
220 ;; The host's version of this allows three choices for 'expanding-into'
221 ;; up until such time as the DEFMACRO is seen (again) for DEFSTRUCT,
222 ;; at which point things are ok because 'early-package' will have been
223 ;; processed. The target has only one possibility.
224 (aver (member expanding-into-code-for '(:target
225 #-sb-xc :cold-target
226 #-sb-xc :host)))
227 (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
228 name-and-options slot-descriptions))
229 (name (dd-name dd))
230 (inherits
231 (if (dd-class-p dd)
232 #+sb-xc-host (!inherits-for-structure dd)
233 #-sb-xc-host
234 (let ((super (compiler-layout-or-lose (or (first (dd-include dd))
235 'structure-object))))
236 (concatenate 'simple-vector
237 (layout-inherits super) (vector super)))))
238 (print-method
239 (when (dd-print-option dd)
240 (let* ((x (sb!xc:gensym "OBJECT"))
241 (s (sb!xc:gensym "STREAM"))
242 (fname (dd-printer-fname dd))
243 (depthp (eq (dd-print-option dd) :print-function)))
244 ;; Giving empty :PRINT-OBJECT or :PRINT-FUNCTION options
245 ;; leaves FNAME eq to NIL. The user-level effect is
246 ;; to generate a PRINT-OBJECT method specialized for the type,
247 ;; implementing the default #S structure-printing behavior.
248 (cond ((not fname)
249 (setf fname 'default-structure-print depthp t))
250 ((not (symbolp fname))
251 ;; Don't dump the source form into the DD constant;
252 ;; just indicate that there was an expression there.
253 (setf (dd-printer-fname dd) t)))
254 `((sb!xc:defmethod print-object ((,x ,name) ,s)
255 (funcall #',fname ,x ,s
256 ,@(if depthp `(*current-level-in-print*)))))))))
257 `(progn
258 ,@(if (dd-class-p dd)
259 `(,@(when (eq expanding-into-code-for :target)
260 `((eval-when (:compile-toplevel :load-toplevel :execute)
261 ;; Note we intentionally enforce package locks and
262 ;; call %DEFSTRUCT first, and especially before
263 ;; %COMPILER-DEFSTRUCT. %DEFSTRUCT has the tests (and
264 ;; resulting CERROR) for collisions with LAYOUTs which
265 ;; already exist in the runtime. If there are any
266 ;; collisions, we want the user's response to CERROR
267 ;; to control what happens. Especially, if the user
268 ;; responds to the collision with ABORT, we don't want
269 ;; %COMPILER-DEFSTRUCT to modify the definition of the
270 ;; class.
271 (%defstruct-package-locks ',dd))))
272 (%defstruct ',dd ',inherits (sb!c:source-location))
273 (eval-when (:compile-toplevel :load-toplevel :execute)
274 (%compiler-defstruct ',dd ',inherits))
275 ,@(unless (eq expanding-into-code-for :host)
276 `((delay-defstruct-functions
277 ,name
278 (progn ,@(awhen (copier-definition dd) (list it))
279 ,@(awhen (predicate-definition dd) (list it))
280 ,@(accessor-definitions dd)))
281 ;; This must be in the same lexical environment
282 ,@(constructor-definitions dd)
283 ,@print-method
284 ;; Various other operations only make sense on the target SBCL.
285 (%target-defstruct ',dd))))
286 `((eval-when (:compile-toplevel :load-toplevel :execute)
287 (setf (info :typed-structure :info ',name) ',dd))
288 (setf (info :source-location :typed-structure ',name)
289 (sb!c:source-location))
290 ,@(unless (eq expanding-into-code-for :host)
291 (append (typed-accessor-definitions dd)
292 (typed-predicate-definitions dd)
293 (typed-copier-definitions dd)
294 (constructor-definitions dd)
295 (when (dd-doc dd)
296 `((setf (fdocumentation ',(dd-name dd) 'structure)
297 ',(dd-doc dd))))))))
298 ',name)))
300 #+sb-xc-host
301 (sb!xc:defmacro defstruct (name-and-options &rest slot-descriptions)
302 (%expander-for-defstruct name-and-options slot-descriptions :cold-target))
304 #+sb-xc
305 (sb!xc:defmacro defstruct (name-and-options &rest slot-descriptions)
306 #!+sb-doc
307 "DEFSTRUCT {Name | (Name Option*)} [Documentation] {Slot | (Slot [Default] {Key Value}*)}
308 Define the structure type Name. Instances are created by MAKE-<name>,
309 which takes &KEY arguments allowing initial slot values to the specified.
310 A SETF'able function <name>-<slot> is defined for each slot to read and
311 write slot values. <name>-p is a type predicate.
313 Popular DEFSTRUCT options (see manual for others):
315 (:CONSTRUCTOR Name)
316 (:PREDICATE Name)
317 Specify the name for the constructor or predicate.
319 (:CONSTRUCTOR Name Lambda-List)
320 Specify the name and arguments for a BOA constructor
321 (which is more efficient when keyword syntax isn't necessary.)
323 (:INCLUDE Supertype Slot-Spec*)
324 Make this type a subtype of the structure type Supertype. The optional
325 Slot-Specs override inherited slot options.
327 Slot options:
329 :TYPE Type-Spec
330 Asserts that the value of this slot is always of the specified type.
332 :READ-ONLY {T | NIL}
333 If true, no setter function is defined for this slot."
334 (%expander-for-defstruct name-and-options slot-descriptions :target))
335 #+sb-xc-host
336 (defmacro sb!xc:defstruct (name-and-options &rest slot-descriptions)
337 #!+sb-doc
338 "Cause information about a target structure to be built into the
339 cross-compiler."
340 (%expander-for-defstruct name-and-options slot-descriptions :host))
342 ;;;; functions to generate code for various parts of DEFSTRUCT definitions
344 ;;; First, a helper to determine whether a name names an inherited
345 ;;; accessor.
346 (defun accessor-inherited-data (name defstruct)
347 (assoc name (dd-inherited-accessor-alist defstruct) :test #'eq))
349 ;;; Return a list of forms which create a predicate function for a
350 ;;; typed DEFSTRUCT.
351 (defun typed-predicate-definitions (defstruct)
352 (let ((name (dd-name defstruct))
353 (predicate-name (dd-predicate-name defstruct))
354 (argname 'x)) ; KISS: no user code appears in the DEFUN
355 (when predicate-name
356 (aver (dd-named defstruct))
357 (let ((ltype (dd-lisp-type defstruct))
358 (name-index (cdr (car (last (find-name-indices defstruct))))))
359 `((defun ,predicate-name (,argname)
360 (and (typep ,argname ',ltype)
361 ,(cond
362 ((subtypep ltype 'list)
363 `(do ((head (the ,ltype ,argname) (cdr head))
364 (i 0 (1+ i)))
365 ((or (not (consp head)) (= i ,name-index))
366 (and (consp head) (eq ',name (car head))))))
367 ((subtypep ltype 'vector)
368 `(and (>= (length (the ,ltype ,argname))
369 ,(dd-length defstruct))
370 (eq ',name (aref (the ,ltype ,argname) ,name-index))))
371 (t (bug "Uncatered-for lisp type in typed DEFSTRUCT: ~S."
372 ltype))))))))))
374 ;;; Return a list of forms to create a copier function of a typed DEFSTRUCT.
375 (defun typed-copier-definitions (defstruct)
376 (when (dd-copier-name defstruct)
377 `((setf (fdefinition ',(dd-copier-name defstruct)) #'copy-seq)
378 (declaim (ftype function ,(dd-copier-name defstruct))))))
380 ;;; Return a list of function definitions for accessing and setting
381 ;;; the slots of a typed DEFSTRUCT. The functions are proclaimed to be
382 ;;; inline, and the types of their arguments and results are declared
383 ;;; as well. We count on the compiler to do clever things with ELT.
384 (defun typed-accessor-definitions (defstruct)
385 (collect ((stuff))
386 (let ((ltype (dd-lisp-type defstruct)))
387 (dolist (slot (dd-slots defstruct))
388 (let ((name (dsd-accessor-name slot))
389 (index (dsd-index slot))
390 (new-value '(value))
391 (slot-type `(and ,(dsd-type slot)
392 ,(dd-element-type defstruct))))
393 (let ((inherited (accessor-inherited-data name defstruct)))
394 (cond
395 ((not inherited)
396 (stuff `(declaim (inline ,name ,@(unless (dsd-read-only slot)
397 `((setf ,name))))))
398 (stuff `(defun ,name (structure)
399 (declare (type ,ltype structure))
400 (the ,slot-type (elt structure ,index))))
401 (unless (dsd-read-only slot)
402 (stuff
403 `(defun (setf ,name) (,(car new-value) structure)
404 (declare (type ,ltype structure) (type ,slot-type . ,new-value))
405 (setf (elt structure ,index) . ,new-value)))))
406 ((not (= (cdr inherited) index))
407 (style-warn "~@<Non-overwritten accessor ~S does not access ~
408 slot with name ~S (accessing an inherited slot ~
409 instead).~:@>" name (dsd-name slot))))))))
410 (stuff)))
412 ;;;; parsing
414 ;;; CLHS says that
415 ;;; A defstruct option can be either a keyword or a list of a keyword
416 ;;; and arguments for that keyword; specifying the keyword by itself is
417 ;;; equivalent to specifying a list consisting of the keyword
418 ;;; and no arguments.
419 ;;; It is unclear whether that is meant to imply that any of the keywords
420 ;;; may be present in their atom form, or only if the grammar at the top
421 ;;; shows the atom form does <atom> have the meaning of (<atom>).
422 ;;; At least one other implementation accepts :NAMED as a singleton list.
423 ;; We take a more rigid view that the depicted grammar is exhaustive.
425 (defconstant-eqx +dd-option-names+
426 ;; Each keyword, except :CONSTRUCTOR which may appear more than once,
427 ;; and :NAMED which is trivial, and unambiguous if present more than
428 ;; once, though possibly worth a style-warning.
429 #(:include ; at least 1 argument
430 :initial-offset ; exactly 1 argument
431 :pure ; exactly 1 argument [nonstandard]
432 :type ; exactly 1 argument
433 :conc-name ; 0 or 1 arg
434 :copier ; "
435 :predicate ; "
436 :print-function ; "
437 :print-object) ; "
438 #'equalp)
440 ;;; Parse a single DEFSTRUCT option and store the results in DD.
441 (defun parse-1-dd-option (option dd seen-options)
442 (let* ((keyword (first option))
443 (bit (position keyword +dd-option-names+))
444 (args (rest option))
445 (arg-p (consp args))
446 (arg (if arg-p (car args)))
447 (name (dd-name dd)))
448 (declare (type (unsigned-byte 9) seen-options)) ; mask over DD-OPTION-NAMES
449 (when bit
450 (if (logbitp bit seen-options)
451 (error "More than one ~S option is not allowed" keyword)
452 (setf seen-options (logior seen-options (ash 1 bit))))
453 (multiple-value-bind (syntax-group winp)
454 (cond ; Perform checking per comment at +DD-OPTION-NAMES+.
455 ((= bit 0) (values 0 (and arg-p (proper-list-p args)))) ; >1 arg
456 ((< bit 4) (values 1 (and arg-p (not (cdr args))))) ; exactly 1
457 (t (values 2 (or (not args) (singleton-p args))))) ; 0 or 1
458 (unless winp
459 (if (proper-list-p option)
460 (error "DEFSTRUCT option ~S ~[requires at least~;~
461 requires exactly~;accepts at most~] one argument" keyword syntax-group)
462 (error "Invalid syntax in DEFSTRUCT option ~S" option)))))
463 (case keyword
464 (:conc-name
465 ;; unlike (:predicate) and (:copier) which mean "yes" if supplied
466 ;; without their argument, (:conc-name) and :conc-name mean no conc-name.
467 ;; Also note a subtle difference in :conc-name "" vs :conc-name NIL.
468 ;; The former re-interns each slot name into *PACKAGE* which might
469 ;; not be the same as using the given name directly as an accessor.
470 (setf (dd-conc-name dd) (if arg (string arg))))
471 (:constructor ; takes 0 to 2 arguments.
472 (destructuring-bind (&optional (cname (symbolicate "MAKE-" name))
473 lambda-list) args
474 (declare (ignore lambda-list))
475 (push (cons cname (cdr args)) (dd-constructors dd))))
476 (:copier
477 (setf (dd-copier-name dd) (if arg-p arg (symbolicate "COPY-" name))))
478 (:predicate
479 (setf (dd-predicate-name dd) (if arg-p arg (symbolicate name "-P"))))
480 (:include
481 (setf (dd-include dd) args))
482 ((:print-function :print-object)
483 (when (dd-print-option dd)
484 (error "~S and ~S may not both be specified"
485 (dd-print-option dd) keyword))
486 (setf (dd-print-option dd) keyword (dd-printer-fname dd) arg))
487 (:type
488 (cond ((member arg '(list vector))
489 (setf (dd-type dd) arg (dd-element-type dd) t))
490 ((and (listp arg) (eq (first arg) 'vector))
491 (destructuring-bind (elt-type) (cdr arg)
492 (setf (dd-type dd) 'vector (dd-element-type dd) elt-type)))
494 (error "~S is a bad :TYPE for DEFSTRUCT." arg))))
495 (:named
496 (error "The DEFSTRUCT option :NAMED takes no arguments."))
497 (:initial-offset
498 (setf (dd-offset dd) arg)) ; FIXME: disallow (:INITIAL-OFFSET NIL)
499 (:pure
500 (setf (dd-pure dd) arg))
502 (error "unknown DEFSTRUCT option:~% ~S" option)))
503 seen-options))
505 ;;; Given name and options, return a DD holding that info.
506 (defun parse-defstruct-name-and-options (name-and-options)
507 (destructuring-bind (name &rest options) name-and-options
508 (let ((dd (make-defstruct-description name))
509 (seen-options 0))
510 (dolist (option options)
511 (if (eq option :named)
512 (setf (dd-named dd) t)
513 (setq seen-options
514 (parse-1-dd-option
515 (cond ((consp option) option)
516 ((member option
517 '(:conc-name :constructor :copier :predicate))
518 (list option))
520 ;; FIXME: ugly message (defstruct (s :include) a)
521 ;; saying "unrecognized" when it means "bad syntax"
522 (error "unrecognized DEFSTRUCT option: ~S" option)))
523 dd seen-options))))
524 (case (dd-type dd)
525 (structure
526 (when (dd-offset dd)
527 (error ":OFFSET can't be specified unless :TYPE is specified."))
528 (unless (dd-include dd)
529 ;; FIXME: It'd be cleaner to treat no-:INCLUDE as defaulting
530 ;; to :INCLUDE STRUCTURE-OBJECT, and then let the general-case
531 ;; (INCF (DD-LENGTH DD) (DD-LENGTH included-DD)) logic take
532 ;; care of this. (Except that the :TYPE VECTOR and :TYPE
533 ;; LIST cases, with their :NAMED and un-:NAMED flavors,
534 ;; make that messy, alas.)
535 (incf (dd-length dd))))
537 ;; In case we are here, :TYPE is specified.
538 (if (dd-named dd)
539 ;; CLHS - "The structure can be :named only if the type SYMBOL
540 ;; is a subtype of the supplied element-type."
541 (multiple-value-bind (winp certainp)
542 (subtypep 'symbol (dd-element-type dd))
543 (when (and (not winp) certainp)
544 (error ":NAMED option is incompatible with element type ~S"
545 (dd-element-type dd))))
546 (when (dd-predicate-name dd)
547 (error ":PREDICATE cannot be used with :TYPE ~
548 unless :NAMED is also specified.")))
549 (awhen (dd-print-option dd)
550 (error ":TYPE option precludes specification of ~S option" it))
551 (when (dd-named dd)
552 (incf (dd-length dd)))
553 (let ((offset (dd-offset dd)))
554 (when offset (incf (dd-length dd) offset)))))
556 (flet ((option-present-p (bit-name)
557 (logbitp (position bit-name +dd-option-names+) seen-options)))
558 (declare (inline option-present-p))
559 (when (and (not (option-present-p :predicate))
560 (or (dd-class-p dd) (dd-named dd)))
561 (setf (dd-predicate-name dd) (symbolicate name "-P")))
562 (unless (option-present-p :conc-name)
563 (setf (dd-conc-name dd) (concatenate 'string (string name) "-")))
564 (unless (option-present-p :copier)
565 (setf (dd-copier-name dd) (symbolicate "COPY-" name))))
566 (when (dd-include dd)
567 (frob-dd-inclusion-stuff dd))
569 dd)))
571 ;;; BOA constructors is (&aux x), i.e. without the default value, the
572 ;;; value of the slot is unspecified, but it should signal a type
573 ;;; error only when it's accessed. safe-p slot in dsd determines
574 ;;; whether to check the type after accessing the slot.
576 ;;; This was performed during boa constructor creating, but the
577 ;;; constructors are created after this information is used to inform
578 ;;; the compiler how to treat such slots.
579 (defun determine-unsafe-slots (dd)
580 (loop for (name lambda-list) in (dd-constructors dd)
581 for &aux = (cdr (member '&aux lambda-list))
583 (loop with name
584 for slot in &aux
585 if (typecase slot
586 ((cons symbol null)
587 (setf name (car slot))
589 (symbol (setf name slot)
591 do (let ((dsd (find name (dd-slots dd)
592 :key #'dsd-name
593 :test #'eq)))
594 (when dsd
595 (setf (dsd-safe-p dsd) nil))))))
597 ;;; Given name and options and slot descriptions (and possibly doc
598 ;;; string at the head of slot descriptions) return a DD holding that
599 ;;; info.
600 (defun parse-defstruct-name-and-options-and-slot-descriptions
601 (name-and-options slot-descriptions)
602 (let ((result (parse-defstruct-name-and-options (if (atom name-and-options)
603 (list name-and-options)
604 name-and-options))))
605 (when (stringp (car slot-descriptions))
606 (setf (dd-doc result) (pop slot-descriptions)))
607 (dolist (slot-description slot-descriptions)
608 (allocate-1-slot result (parse-1-dsd result slot-description)))
609 (determine-unsafe-slots result)
610 result))
612 ;;;; stuff to parse slot descriptions
614 ;;; Parse a slot description for DEFSTRUCT, add it to the description
615 ;;; and return it. If supplied, SLOT is a pre-initialized DSD
616 ;;; that we modify to get the new slot. This is supplied when handling
617 ;;; included slots.
618 (defun parse-1-dsd (defstruct spec &optional
619 (slot (make-defstruct-slot-description :name ""
620 :index 0
621 :type t)))
622 (multiple-value-bind (name default default-p type type-p read-only ro-p)
623 (typecase spec
624 (symbol
625 (typecase spec
626 ((or null (member :conc-name :constructor :copier :predicate :named))
627 (warn "slot name of ~S indicates probable syntax error in DEFSTRUCT" spec))
628 (keyword
629 (style-warn "slot name of ~S indicates possible syntax error in DEFSTRUCT" spec)))
630 spec)
631 (cons
632 (destructuring-bind
633 (name &optional (default nil default-p)
634 &key (type nil type-p) (read-only nil ro-p))
635 spec
636 (when (dd-conc-name defstruct)
637 ;; the warning here is useful, but in principle we cannot
638 ;; distinguish between legitimate and erroneous use of
639 ;; these names when :CONC-NAME is NIL. In the common
640 ;; case (CONC-NAME non-NIL), there are alternative ways
641 ;; of writing code with the same effect, so a full
642 ;; warning is justified.
643 (typecase name
644 ((member :conc-name :constructor :copier :predicate :include
645 :print-function :print-object :type :initial-offset :pure)
646 (warn "slot name of ~S indicates probable syntax error in DEFSTRUCT" name))))
647 (values name default default-p
648 (uncross type) type-p
649 read-only ro-p)))
650 (t (error 'simple-program-error
651 :format-control "in DEFSTRUCT, ~S is not a legal slot ~
652 description."
653 :format-arguments (list spec))))
655 (when (find name (dd-slots defstruct)
656 :test #'string=
657 :key (lambda (x) (symbol-name (dsd-name x))))
658 (error 'simple-program-error
659 ;; Todo: indicate whether name is a duplicate in the directly
660 ;; specified slots vs. exists in the ancestor and so should
661 ;; be in the (:include ...) clause instead of where it is.
662 :format-control "duplicate slot name ~S"
663 :format-arguments (list name)))
664 (setf (dsd-name slot) name)
665 (setf (dd-slots defstruct) (nconc (dd-slots defstruct) (list slot)))
667 (let ((accessor-name (if (dd-conc-name defstruct)
668 (symbolicate (dd-conc-name defstruct) name)
669 name))
670 (predicate-name (dd-predicate-name defstruct)))
671 (setf (dsd-accessor-name slot) accessor-name)
672 (when (eql accessor-name predicate-name)
673 ;; Some adventurous soul has named a slot so that its accessor
674 ;; collides with the structure type predicate. ANSI doesn't
675 ;; specify what to do in this case. As of 2001-09-04, Martin
676 ;; Atzmueller reports that CLISP and Lispworks both give
677 ;; priority to the slot accessor, so that the predicate is
678 ;; overwritten. We might as well do the same (as well as
679 ;; signalling a warning).
680 (style-warn
681 "~@<The structure accessor name ~S is the same as the name of the ~
682 structure type predicate. ANSI doesn't specify what to do in ~
683 this case. We'll overwrite the type predicate with the slot ~
684 accessor, but you can't rely on this behavior, so it'd be wise to ~
685 remove the ambiguity in your code.~@:>"
686 accessor-name)
687 (setf (dd-predicate-name defstruct) nil))
688 ;; FIXME: It would be good to check for name collisions here, but
689 ;; the easy check,
690 ;;x#-sb-xc-host
691 ;;x(when (and (fboundp accessor-name)
692 ;;x (not (accessor-inherited-data accessor-name defstruct)))
693 ;;x (style-warn "redefining ~/sb-impl::print-symbol-with-prefix/ ~
694 ;; in DEFSTRUCT" accessor-name)))
695 ;; which was done until sbcl-0.8.11.18 or so, is wrong: it causes
696 ;; a warning at MACROEXPAND time, when instead the warning should
697 ;; occur not just because the code was constructed, but because it
698 ;; is actually compiled or loaded.
701 (when default-p
702 (setf (dsd-default slot) default))
703 (when type-p
704 (setf (dsd-type slot)
705 (if (eq (dsd-type slot) t)
706 type
707 `(and ,(dsd-type slot) ,type))))
708 (when ro-p
709 (if read-only
710 (setf (dsd-read-only slot) t)
711 (when (dsd-read-only slot)
712 (error "~@<The slot ~S is :READ-ONLY in superclass, and so must ~
713 be :READ-ONLY in subclass.~:@>"
714 (dsd-name slot)))))
715 slot))
717 ;;; When a value of type TYPE is stored in a structure, should it be
718 ;;; stored in a raw slot? Return the matching RAW-SLOT-DATA structure
719 ;; if TYPE should be stored in a raw slot, or NIL if not.
720 (defun structure-raw-slot-data (type)
721 (multiple-value-bind (fixnum? fixnum-certain?)
722 (sb!xc:subtypep type 'fixnum)
723 ;; (The extra test for FIXNUM-CERTAIN? here is intended for
724 ;; bootstrapping the system. In particular, in sbcl-0.6.2, we set up
725 ;; LAYOUT before FIXNUM is defined, and so could bogusly end up
726 ;; putting INDEX-typed values into raw slots if we didn't test
727 ;; FIXNUM-CERTAIN?.)
728 (if (or fixnum? (not fixnum-certain?))
730 (dolist (data *raw-slot-data-list*)
731 (when (sb!xc:subtypep type (raw-slot-data-raw-type data))
732 (return data))))))
734 ;;; Allocate storage for a DSD in DD. This is where we decide whether
735 ;;; a slot is raw or not. Raw objects are aligned on the unit of their size.
736 (defun allocate-1-slot (dd dsd)
737 (let ((rsd (if (eq (dd-type dd) 'structure)
738 (structure-raw-slot-data (dsd-type dsd))
739 nil)))
740 (cond ((null rsd)
741 (setf (dsd-index dsd) (dd-length dd))
742 (incf (dd-length dd)))
744 (setf (dsd-raw-type dsd) (raw-slot-data-raw-type rsd))
745 (let ((words (raw-slot-data-n-words rsd))
746 (alignment (raw-slot-data-alignment rsd)))
747 #!-interleaved-raw-slots
748 (let ((off (rem (dd-raw-length dd) alignment)))
749 (unless (zerop off)
750 (incf (dd-raw-length dd) (- alignment off)))
751 (setf (dsd-index dsd) (dd-raw-length dd))
752 (incf (dd-raw-length dd) words))
753 #!+interleaved-raw-slots
754 (let ((len (dd-length dd)))
755 (setf (dd-length dd)
756 ;; this formula works but can it be made less unclear?
757 (- len (nth-value 1 (ceiling (1- len) alignment))))
758 (setf (dsd-index dsd) (dd-length dd))
759 (incf (dd-length dd) words))))))
760 (values))
762 (defun typed-structure-info-or-lose (name)
763 (or (info :typed-structure :info name)
764 (error ":TYPE'd DEFSTRUCT ~S not found for inclusion." name)))
766 ;;; Process any included slots pretty much like they were specified.
767 ;;; Also inherit various other attributes.
768 (defun frob-dd-inclusion-stuff (dd)
769 (destructuring-bind (included-name &rest modified-slots) (dd-include dd)
770 (let* ((type (dd-type dd))
771 (included-structure
772 (if (dd-class-p dd)
773 (layout-info (compiler-layout-or-lose included-name))
774 (typed-structure-info-or-lose included-name))))
776 ;; checks on legality
777 (unless (and (eq type (dd-type included-structure))
778 (type= (specifier-type (dd-element-type included-structure))
779 (specifier-type (dd-element-type dd))))
780 (error ":TYPE option mismatch between structures ~S and ~S"
781 (dd-name dd) included-name))
782 (let ((included-classoid (find-classoid included-name nil)))
783 (when included-classoid
784 ;; It's not particularly well-defined to :INCLUDE any of the
785 ;; CMU CL INSTANCE weirdosities like CONDITION or
786 ;; GENERIC-FUNCTION, and it's certainly not ANSI-compliant.
787 (let* ((included-layout (classoid-layout included-classoid))
788 (included-dd (layout-info included-layout)))
789 (when (dd-alternate-metaclass included-dd)
790 (error "can't :INCLUDE class ~S (has alternate metaclass)"
791 included-name)))))
793 ;; A few more sanity checks: every allegedly modified slot exists
794 ;; and no name appears more than once.
795 (flet ((included-slot-name (slot-desc)
796 (if (atom slot-desc) slot-desc (car slot-desc))))
797 (mapl (lambda (slots &aux (name (included-slot-name (car slots))))
798 (unless (find name (dd-slots included-structure)
799 :test #'string= :key #'dsd-name)
800 (error 'simple-program-error
801 :format-control "slot name ~S not present in included structure"
802 :format-arguments (list name)))
803 (when (find name (cdr slots)
804 :test #'string= :key #'included-slot-name)
805 (error 'simple-program-error
806 :format-control "included slot name ~S specified more than once"
807 :format-arguments (list name))))
808 modified-slots))
810 (incf (dd-length dd) (dd-length included-structure))
811 (when (dd-class-p dd)
812 (when (eq (dd-pure dd) :unspecified)
813 (setf (dd-pure dd) (dd-pure included-structure)))
814 #!-interleaved-raw-slots
815 (setf (dd-raw-length dd) (dd-raw-length included-structure)))
817 (setf (dd-inherited-accessor-alist dd)
818 (dd-inherited-accessor-alist included-structure))
819 (dolist (included-slot (dd-slots included-structure))
820 (let* ((included-name (dsd-name included-slot))
821 (modified (or (find included-name modified-slots
822 :key (lambda (x) (if (atom x) x (car x)))
823 :test #'string=)
824 `(,included-name))))
825 ;; We stash away an alist of accessors to parents' slots
826 ;; that have already been created to avoid conflicts later
827 ;; so that structures with :INCLUDE and :CONC-NAME (and
828 ;; other edge cases) can work as specified.
829 (when (dsd-accessor-name included-slot)
830 ;; the "oldest" (i.e. highest up the tree of inheritance)
831 ;; will prevail, so don't push new ones on if they
832 ;; conflict.
833 (pushnew (cons (dsd-accessor-name included-slot)
834 (dsd-index included-slot))
835 (dd-inherited-accessor-alist dd)
836 :test #'eq :key #'car))
837 (let ((new-slot (parse-1-dsd dd
838 modified
839 (copy-structure included-slot))))
840 (when (and (neq (dsd-type new-slot) (dsd-type included-slot))
841 (not (sb!xc:subtypep (dsd-type included-slot)
842 (dsd-type new-slot)))
843 (dsd-safe-p included-slot))
844 (setf (dsd-safe-p new-slot) nil)
845 ;; XXX: notify?
846 )))))))
848 ;;;; various helper functions for setting up DEFSTRUCTs
850 ;;; This function is called at macroexpand time to compute the INHERITS
851 ;;; vector for a structure type definition.
852 ;;; The cross-compiler is allowed to magically compute LAYOUT-INHERITS.
853 (defun !inherits-for-structure (info)
854 (declare (type defstruct-description info))
855 (let* ((include (dd-include info))
856 (superclass-opt (dd-alternate-metaclass info))
857 (super
858 (if include
859 (compiler-layout-or-lose (first include))
860 (classoid-layout (find-classoid
861 (or (first superclass-opt)
862 'structure-object))))))
863 (case (dd-name info)
864 ((ansi-stream)
865 ;; STREAM is an abstract class and you can't :include it,
866 ;; so the inheritance has to be hardcoded.
867 (concatenate 'simple-vector
868 (layout-inherits super)
869 (vector super (classoid-layout (find-classoid 'stream)))))
870 ((fd-stream) ; Similarly, FILE-STREAM is abstract
871 (concatenate 'simple-vector
872 (layout-inherits super)
873 (vector super
874 (classoid-layout (find-classoid 'file-stream)))))
875 ((sb!impl::string-input-stream ; etc
876 sb!impl::string-output-stream
877 sb!impl::fill-pointer-output-stream)
878 (concatenate 'simple-vector
879 (layout-inherits super)
880 (vector super
881 (classoid-layout (find-classoid 'string-stream)))))
882 (t (concatenate 'simple-vector
883 (layout-inherits super)
884 (vector super))))))
886 ;;; Do miscellaneous (LOAD EVAL) time actions for the structure
887 ;;; described by DD. Create the class and LAYOUT, checking for
888 ;;; incompatible redefinition.
889 (defun %defstruct (dd inherits source-location)
890 (declare (type defstruct-description dd))
892 ;; We set up LAYOUTs even in the cross-compilation host.
893 (multiple-value-bind (classoid layout old-layout)
894 (ensure-structure-class dd inherits "current" "new")
895 (cond ((not old-layout)
896 (unless (eq (classoid-layout classoid) layout)
897 (register-layout layout)))
899 (%redefine-defstruct classoid old-layout layout)
900 (let ((old-dd (layout-info old-layout)))
901 (when (defstruct-description-p old-dd)
902 (dolist (slot (dd-slots old-dd))
903 (fmakunbound (dsd-accessor-name slot))
904 (unless (dsd-read-only slot)
905 (fmakunbound `(setf ,(dsd-accessor-name slot)))))))
906 (setq layout (classoid-layout classoid))))
907 (setf (find-classoid (dd-name dd)) classoid)
909 (sb!c:with-source-location (source-location)
910 (setf (layout-source-location layout) source-location))))
913 ;;; Return a form describing the writable place used for this slot
914 ;;; in the instance named INSTANCE-NAME.
915 (defun %accessor-place-form (dd dsd instance-name)
916 (let (;; the operator that we'll use to access a typed slot
917 (ref (ecase (dd-type dd)
918 (structure '%instance-ref)
919 (list 'nth-but-with-sane-arg-order)
920 (vector 'aref)))
921 (raw-type (dsd-raw-type dsd)))
922 (if (eq raw-type t) ; if not raw slot
923 `(,ref ,instance-name ,(dsd-index dsd))
924 `(,(raw-slot-data-accessor-name (raw-slot-data-or-lose raw-type))
925 ,instance-name ,(dsd-index dsd)))))
927 ;;; Return the transformation of conceptual FUNCTION (either :READ or :WRITE)
928 ;;; applied to ARGS, given SLOT-KEY which is a cons of a DD and a DSD.
929 ;;; Return NIL on failure.
930 (defun slot-access-transform (function args slot-key)
931 (when (consp args) ; need at least one arg
932 (let* ((dd (car slot-key))
933 (dsd (cdr slot-key))
934 ;; optimistically compute PLACE before checking length of ARGS
935 ;; because we expect success, and this unifies the two cases.
936 ;; :WRITE has the arg order of (SETF fn), i.e. newval is first,
937 ;; so if more than one arg exists, take the second as the INSTANCE.
938 (place
939 (%accessor-place-form
940 dd dsd `(the ,(dd-name dd)
941 ,(car (if (consp (cdr args)) (cdr args) args)))))
942 (type-spec (dsd-type dsd)))
943 (ecase function
944 (:read
945 (when (singleton-p args)
946 (if (eq type-spec t)
947 place
948 `(,(if (dsd-safe-p dsd) 'truly-the 'the) ,type-spec ,place))))
949 (:write
950 (when (singleton-p (cdr args))
951 (once-only ((new (first args)))
952 ;; instance setters take newval last.
953 `(,(info :setf :inverse (car place)) ,@(cdr place)
954 ,(if (eq type-spec t) new `(the ,type-spec ,new))))))))))
956 ;;; Return a LAMBDA form which can be used to set a slot
957 (defun slot-setter-lambda-form (dd dsd)
958 `(lambda (newval instance)
959 ,(slot-access-transform :write '(newval instance) (cons dd dsd))))
961 ;;; Blow away all the compiler info for the structure CLASS. Iterate
962 ;;; over this type, clearing the compiler structure type info, and
963 ;;; undefining all the associated functions. If SUBCLASSES-P, also do
964 ;;; the same for subclasses. FIXME: maybe rename UNDEFINE-FUN-NAME to
965 ;;; UNDECLARE-FUNCTION-NAME?
966 (defun undeclare-structure (classoid subclasses-p)
967 (let ((info (layout-info (classoid-layout classoid))))
968 (when (defstruct-description-p info)
969 (let ((type (dd-name info)))
970 (clear-info :type :compiler-layout type)
971 (undefine-fun-name (dd-copier-name info))
972 (undefine-fun-name (dd-predicate-name info))
973 (dolist (slot (dd-slots info))
974 (let ((fun (dsd-accessor-name slot)))
975 (unless (accessor-inherited-data fun info)
976 (undefine-fun-name fun)
977 (unless (dsd-read-only slot)
978 (undefine-fun-name `(setf ,fun)))))))
979 ;; Clear out the SPECIFIER-TYPE cache so that subsequent
980 ;; references are unknown types.
981 (values-specifier-type-cache-clear)))
982 (when subclasses-p
983 (let ((subclasses (classoid-subclasses classoid)))
984 (when subclasses
985 (collect ((subs))
986 (dohash ((classoid layout)
987 subclasses
988 :locked t)
989 (declare (ignore layout))
990 (undeclare-structure classoid nil)
991 (subs (classoid-proper-name classoid)))
992 ;; Is it really necessary to warn about
993 ;; undeclaring functions for subclasses?
994 (when (subs)
995 (warn "undeclaring functions for old subclasses ~
996 of ~S:~% ~S"
997 (classoid-name classoid)
998 (subs))))))))
1000 ;;; core compile-time setup of any class with a LAYOUT, used even by
1001 ;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS weirdosities
1002 (defun %compiler-set-up-layout (dd
1003 &optional
1004 ;; Several special cases
1005 ;; (STRUCTURE-OBJECT itself, and
1006 ;; structures with alternate
1007 ;; metaclasses) call this function
1008 ;; directly, and they're all at the
1009 ;; base of the instance class
1010 ;; structure, so this is a handy
1011 ;; default. (But note
1012 ;; FUNCALLABLE-STRUCTUREs need
1013 ;; assistance here)
1014 (inherits (vector (find-layout t))))
1016 (multiple-value-bind (classoid layout old-layout)
1017 (multiple-value-bind (clayout clayout-p)
1018 (info :type :compiler-layout (dd-name dd))
1019 (ensure-structure-class dd
1020 inherits
1021 (if clayout-p
1022 "The most recently compiled"
1023 "The current")
1024 "the most recently loaded"
1025 :compiler-layout clayout))
1026 (cond (old-layout
1027 (undeclare-structure (layout-classoid old-layout)
1028 (and (classoid-subclasses classoid)
1029 (not (eq layout old-layout))))
1030 (setf (layout-invalid layout) nil)
1031 ;; FIXME: it might be polite to hold onto old-layout and
1032 ;; restore it at the end of the file. -- RMK 2008-09-19
1033 ;; (International Talk Like a Pirate Day).
1034 (warn "~@<Clobbering the compiler's idea of the layout of ~A.~:@>"
1035 classoid))
1037 (unless (eq (classoid-layout classoid) layout)
1038 (register-layout layout :invalidate nil))
1039 (setf (find-classoid (dd-name dd)) classoid)))
1041 ;; At this point the class should be set up in the INFO database.
1042 ;; But the logic that enforces this is a little tangled and
1043 ;; scattered, so it's not obvious, so let's check.
1044 (aver (find-classoid (dd-name dd) nil))
1046 (setf (info :type :compiler-layout (dd-name dd)) layout))
1047 (values))
1049 ;;; Do (COMPILE LOAD EVAL)-time actions for the normal (not
1050 ;;; ALTERNATE-LAYOUT) DEFSTRUCT described by DD.
1051 ;;; This includes generation of a style-warning about previously compiled
1052 ;;; calls to the accessors and/or predicate that weren't inlined.
1053 (defun %compiler-defstruct (dd inherits)
1054 (declare (type defstruct-description dd))
1056 (aver (dd-class-p dd)) ; LIST and VECTOR representation are not allowed
1057 (let ((check-inlining
1058 ;; Why use the secondary result of INFO, not the primary?
1059 ;; Because when DEFSTRUCT is evaluated, not via the file-compiler,
1060 ;; the first thing to happen is %DEFSTRUCT, which sets up FIND-CLASS.
1061 ;; Due to :COMPILER-LAYOUT's defaulting expression in globaldb,
1062 ;; it has a value - the layout of the classoid - that we don't want.
1063 ;; Also, since structures are technically not redefineable,
1064 ;; I don't worry about failure to inline a function that was
1065 ;; formerly not known as an accessor but now is.
1066 (null (nth-value 1 (info :type :compiler-layout (dd-name dd)))))
1067 (fnames))
1068 (%compiler-set-up-layout dd inherits)
1070 (awhen (dd-copier-name dd)
1071 (let ((dtype (dd-name dd)))
1072 (sb!xc:proclaim `(ftype (sfunction (,dtype) ,dtype) ,it))))
1074 (let ((predicate-name (dd-predicate-name dd)))
1075 (when predicate-name
1076 (when check-inlining
1077 (push predicate-name fnames))
1078 (setf (info :function :source-transform predicate-name)
1079 (cons dd :predicate))))
1081 (dolist (dsd (dd-slots dd))
1082 (let ((accessor-name (dsd-accessor-name dsd)))
1083 ;; Why this WHEN guard here, if there is neither a standards-specified
1084 ;; nor implementation-specific way to skip defining an accessor? Dunno.
1085 ;; And furthermore, by ignoring a package lock, it's possible to name
1086 ;; an accessor NIL: (defstruct (x (:conc-name "N")) IL)
1087 ;; making this test kinda bogus in two different ways.
1088 (when accessor-name
1089 (let ((inherited (accessor-inherited-data accessor-name dd)))
1090 (cond
1091 ((not inherited)
1092 (let ((writer `(setf ,accessor-name))
1093 (slot-key (cons dd dsd)))
1094 (when check-inlining
1095 (push accessor-name fnames))
1096 (setf (info :function :source-transform accessor-name)
1097 slot-key)
1098 (unless (dsd-read-only dsd)
1099 (when check-inlining
1100 (push writer fnames))
1101 (setf (info :function :source-transform writer) slot-key))))
1102 ((not (= (cdr inherited) (dsd-index dsd)))
1103 (style-warn "~@<Non-overwritten accessor ~S does not access ~
1104 slot with name ~S (accessing an inherited slot ~
1105 instead).~:@>"
1106 accessor-name
1107 (dsd-name dsd))))))))
1109 (awhen (remove-if-not #'sb!c::emitted-full-call-count fnames)
1110 (sb!c:compiler-style-warn
1111 'sb!c:inlining-dependency-failure
1112 ;; This message omits the http://en.wikipedia.org/wiki/Serial_comma
1113 :format-control
1114 (!uncross-format-control
1115 "~@<Previously compiled call~P to ~
1116 ~{~/sb!impl:print-symbol-with-prefix/~^~#[~; and~:;,~] ~} ~
1117 could not be inlined because the structure definition for ~
1118 ~/sb!impl:print-symbol-with-prefix/ was not yet seen. To avoid this warning, ~
1119 DEFSTRUCT should precede references to the affected functions, ~
1120 or they must be declared locally notinline at each call site.~@:>")
1121 :format-arguments (list (length it) (nreverse it) (dd-name dd))))))
1123 ;;;; redefinition stuff
1125 ;;; Compare the slots of OLD and NEW, returning 3 lists of slot names:
1126 ;;; 1. Slots which have moved,
1127 ;;; 2. Slots whose type has changed,
1128 ;;; 3. Deleted slots.
1129 (defun compare-slots (old new)
1130 (let* ((oslots (dd-slots old))
1131 (nslots (dd-slots new))
1132 (onames (mapcar #'dsd-name oslots))
1133 (nnames (mapcar #'dsd-name nslots)))
1134 (collect ((moved)
1135 (retyped))
1136 (dolist (name (intersection onames nnames))
1137 (let ((os (find name oslots :key #'dsd-name :test #'string=))
1138 (ns (find name nslots :key #'dsd-name :test #'string=)))
1139 (unless (sb!xc:subtypep (dsd-type ns) (dsd-type os))
1140 (retyped name))
1141 (unless (and (= (dsd-index os) (dsd-index ns))
1142 (eq (dsd-raw-type os) (dsd-raw-type ns)))
1143 (moved name))))
1144 (values (moved)
1145 (retyped)
1146 (set-difference onames nnames :test #'string=)))))
1148 ;;; If we are redefining a structure with different slots than in the
1149 ;;; currently loaded version, give a warning and return true.
1150 (defun redefine-structure-warning (classoid old new)
1151 (declare (type defstruct-description old new)
1152 (type classoid classoid)
1153 (ignore classoid))
1154 (let ((name (dd-name new)))
1155 (multiple-value-bind (moved retyped deleted) (compare-slots old new)
1156 (when (or moved retyped deleted)
1157 (warn
1158 "incompatibly redefining slots of structure class ~S~@
1159 Make sure any uses of affected accessors are recompiled:~@
1160 ~@[ These slots were moved to new positions:~% ~S~%~]~
1161 ~@[ These slots have new incompatible types:~% ~S~%~]~
1162 ~@[ These slots were deleted:~% ~S~%~]"
1163 name moved retyped deleted)
1164 t))))
1166 ;;; This function is called when we are incompatibly redefining a
1167 ;;; structure CLASS to have the specified NEW-LAYOUT. We signal an
1168 ;;; error with some proceed options and return the layout that should
1169 ;;; be used.
1170 (defun %redefine-defstruct (classoid old-layout new-layout)
1171 (declare (type classoid classoid)
1172 (type layout old-layout new-layout))
1173 (let ((name (classoid-proper-name classoid)))
1174 (restart-case
1175 (error "~@<attempt to redefine the ~S class ~S incompatibly with the current definition~:@>"
1176 'structure-object
1177 name)
1178 (continue ()
1179 :report (lambda (s)
1180 (format s
1181 "~@<Use the new definition of ~S, invalidating ~
1182 already-loaded code and instances.~@:>"
1183 name))
1184 (register-layout new-layout))
1185 (recklessly-continue ()
1186 :report (lambda (s)
1187 (format s
1188 "~@<Use the new definition of ~S as if it were ~
1189 compatible, allowing old accessors to use new ~
1190 instances and allowing new accessors to use old ~
1191 instances.~@:>"
1192 name))
1193 ;; classic CMU CL warning: "Any old ~S instances will be in a bad way.
1194 ;; I hope you know what you're doing..."
1195 (register-layout new-layout
1196 :invalidate nil
1197 :destruct-layout old-layout))
1198 (clobber-it ()
1199 ;; FIXME: deprecated 2002-10-16, and since it's only interactive
1200 ;; hackery instead of a supported feature, can probably be deleted
1201 ;; in early 2003
1202 :report "(deprecated synonym for RECKLESSLY-CONTINUE)"
1203 (register-layout new-layout
1204 :invalidate nil
1205 :destruct-layout old-layout))))
1206 (values))
1208 (declaim (inline dd-layout-length))
1209 (defun dd-layout-length (dd)
1210 (+ (dd-length dd) #!-interleaved-raw-slots (dd-raw-length dd)))
1212 (declaim (ftype (sfunction (defstruct-description) index) dd-instance-length))
1213 (defun dd-instance-length (dd)
1214 ;; Make sure the object ends at a two-word boundary. Note that this does
1215 ;; not affect the amount of memory used, since the allocator would add the
1216 ;; same padding anyway. However, raw slots are indexed from the length of
1217 ;; the object as indicated in the header, so the pad word needs to be
1218 ;; included in that length to guarantee proper alignment of raw double float
1219 ;; slots, necessary for (at least) the SPARC backend.
1220 ;; On backends with interleaved raw slots, the convention of having the
1221 ;; header possibly "lie" about an extra word is more of a bug than a feature.
1222 ;; Because the structure base is aligned, double-word raw slots are properly
1223 ;; aligned, and won't change alignment in descendant object types. It would
1224 ;; be correct to store the true instance length even though GC preserves
1225 ;; the extra data word (as it does for odd-length SIMPLE-VECTOR), treating
1226 ;; the total physical length as rounded-to-even. But having two different
1227 ;; conventions would be even more unnecessarily confusing, so we use
1228 ;; the not-sensible convention even when it does not make sense.
1229 (logior (dd-layout-length dd) 1))
1231 (defun dd-bitmap (dd)
1232 ;; The bitmap stores a 1 for each untagged word,
1233 ;; including any internal padding words for alignment.
1234 ;; The 0th bit is initialized to 0 because the LAYOUT is a tagged
1235 ;; slot that is not present in DD-SLOTS.
1236 ;; All other bits start as 1 and are cleared if the word is tagged.
1237 ;; A final padding word, if any, is regarded as tagged.
1238 (let ((bitmap (ldb (byte (dd-length dd) 0)
1239 (ash -1 sb!vm:instance-data-start))))
1240 (dolist (slot (dd-slots dd) bitmap)
1241 (when (eql t (dsd-raw-type slot))
1242 (setf (ldb (byte 1 (dsd-index slot)) bitmap) 0)))))
1244 ;;; This is called when we are about to define a structure class. It
1245 ;;; returns a (possibly new) class object and the layout which should
1246 ;;; be used for the new definition (may be the current layout, and
1247 ;;; also might be an uninstalled forward referenced layout.) The third
1248 ;;; value is true if this is an incompatible redefinition, in which
1249 ;;; case it is the old layout.
1250 (defun ensure-structure-class (info inherits old-context new-context
1251 &key compiler-layout)
1252 (declare (type defstruct-description info))
1253 (multiple-value-bind (class old-layout)
1254 (multiple-value-bind (class constructor)
1255 (acond ((cdr (dd-alternate-metaclass info))
1256 (values (first it) (second it)))
1258 (values 'structure-classoid 'make-structure-classoid)))
1259 (insured-find-classoid (dd-name info)
1260 (if (eq class 'structure-classoid)
1261 (lambda (x)
1262 (sb!xc:typep x 'structure-classoid))
1263 (lambda (x)
1264 (sb!xc:typep x (classoid-name (find-classoid class)))))
1265 (fdefinition constructor)))
1266 (setf (classoid-direct-superclasses class)
1267 (case (dd-name info)
1268 ((ansi-stream
1269 fd-stream
1270 sb!impl::string-input-stream sb!impl::string-output-stream
1271 sb!impl::fill-pointer-output-stream)
1272 (list (layout-classoid (svref inherits (1- (length inherits))))
1273 (layout-classoid (svref inherits (- (length inherits) 2)))))
1275 (list (layout-classoid
1276 (svref inherits (1- (length inherits))))))))
1277 (let* ((old-layout (or compiler-layout old-layout))
1278 (new-layout
1279 (when (or (not old-layout) *type-system-initialized*)
1280 (make-layout :classoid class
1281 :inherits inherits
1282 :depthoid (length inherits)
1283 :length (dd-layout-length info)
1284 :info info . #!-interleaved-raw-slots
1285 (:n-untagged-slots (dd-raw-length info))
1286 #!+interleaved-raw-slots
1287 (:untagged-bitmap (dd-bitmap info))))))
1288 (cond
1289 ((not old-layout)
1290 (values class new-layout nil))
1291 ((not new-layout)
1292 ;; The assignment of INFO here can almost be deleted,
1293 ;; except for a few magical types that don't d.t.r.t. in cold-init:
1294 ;; STRUCTURE-OBJECT, CONDITION, ALIEN-VALUE, INTERPRETED-FUNCTION
1295 (setf (layout-info old-layout) info)
1296 (values class old-layout nil))
1297 (;; This clause corresponds to an assertion in REDEFINE-LAYOUT-WARNING
1298 ;; of classic CMU CL. I moved it out to here because it was only
1299 ;; exercised in this code path anyway. -- WHN 19990510
1300 (not (eq (layout-classoid new-layout) (layout-classoid old-layout)))
1301 (error "shouldn't happen: weird state of OLD-LAYOUT?"))
1302 ((redefine-layout-warning old-context
1303 old-layout
1304 new-context
1305 (layout-length new-layout)
1306 (layout-inherits new-layout)
1307 (layout-depthoid new-layout)
1308 (layout-raw-slot-metadata new-layout))
1309 (values class new-layout old-layout))
1311 (let ((old-info (layout-info old-layout)))
1312 (if old-info
1313 (cond ((redefine-structure-warning class old-info info)
1314 (values class new-layout old-layout))
1316 (setf (layout-info old-layout) info)
1317 (values class old-layout nil)))
1318 (progn
1319 (setf (layout-info old-layout) info)
1320 (values class old-layout nil)))))))))
1322 ;;; Return a list of pairs (name . index). Used for :TYPE'd
1323 ;;; constructors to find all the names that we have to splice in &
1324 ;;; where. Note that these types don't have a layout, so we can't look
1325 ;;; at LAYOUT-INHERITS.
1326 (defun find-name-indices (defstruct)
1327 (collect ((res))
1328 (let ((infos ()))
1329 (do ((info defstruct
1330 (typed-structure-info-or-lose (first (dd-include info)))))
1331 ((not (dd-include info))
1332 (push info infos))
1333 (push info infos))
1335 (let ((i 0))
1336 (dolist (info infos)
1337 (incf i (or (dd-offset info) 0))
1338 (when (dd-named info)
1339 (res (cons (dd-name info) i)))
1340 (setq i (dd-length info)))))
1342 (res)))
1344 ;;; These functions are called to actually make a constructor after we
1345 ;;; have processed the arglist. The correct variant (according to the
1346 ;;; DD-TYPE) should be called. The function is defined with the
1347 ;;; specified name and arglist. VARS and TYPES are used for argument
1348 ;;; type declarations. VALUES are the values for the slots (in order.)
1350 ;;; This is split three ways because:
1351 ;;; * LIST & VECTOR structures need "name" symbols stuck in at
1352 ;;; various weird places, whereas STRUCTURE structures have
1353 ;;; a LAYOUT slot.
1354 ;;; * We really want to use LIST to make list structures, instead of
1355 ;;; MAKE-LIST/(SETF ELT). (We can't in general use VECTOR in an
1356 ;;; analogous way, since VECTOR makes a SIMPLE-VECTOR and vector-typed
1357 ;;; structures can have arbitrary subtypes of VECTOR, not necessarily
1358 ;;; SIMPLE-VECTOR.)
1359 ;;; * STRUCTURE structures can have raw slots that must also be
1360 ;;; allocated and indirectly referenced.
1361 (defun create-vector-constructor (dd cons-name arglist ftype-arglist decls values)
1362 (let ((temp (gensym))
1363 (etype (dd-element-type dd))
1364 (len (dd-length dd)))
1365 (values
1366 `(defun ,cons-name ,arglist
1367 ,@(when decls `((declare ,@decls)))
1368 (let ((,temp (make-array ,len :element-type ',etype)))
1369 ,@(mapcar (lambda (x)
1370 `(setf (aref ,temp ,(cdr x)) ',(car x)))
1371 (find-name-indices dd))
1372 ,@(mapcar (lambda (dsd value)
1373 (unless (eq value '.do-not-initialize-slot.)
1374 `(setf (aref ,temp ,(dsd-index dsd)) ,value)))
1375 (dd-slots dd) values)
1376 ,temp))
1377 `(sfunction ,ftype-arglist (simple-array ,etype (,len))))))
1378 (defun create-list-constructor (dd cons-name arglist ftype-arglist decls values)
1379 (let ((vals (make-list (dd-length dd) :initial-element nil)))
1380 (dolist (x (find-name-indices dd))
1381 (setf (elt vals (cdr x)) `',(car x)))
1382 (loop for dsd in (dd-slots dd) and val in values do
1383 (setf (elt vals (dsd-index dsd))
1384 (if (eq val '.do-not-initialize-slot.) 0 val)))
1385 (values
1386 `(defun ,cons-name ,arglist
1387 ,@(when decls `((declare ,@decls)))
1388 (list ,@vals))
1389 `(sfunction ,ftype-arglist list))))
1390 (defun create-structure-constructor (dd cons-name arglist ftype-arglist decls values)
1391 (values
1392 ;; The difference between the two implementations here is that on all
1393 ;; platforms we don't have the appropriate RAW-INSTANCE-INIT VOPS, which
1394 ;; must be able to deal with immediate values as well -- unlike
1395 ;; RAW-INSTANCE-SET VOPs, which never end up seeing immediate values. With
1396 ;; some additional cleverness we might manage without them and just a single
1397 ;; implementation here, though -- figure out a way to ensure that on those
1398 ;; platforms we always still get a non-immediate TN in every case...
1400 ;; Until someone does that, this means that instances with raw slots can be
1401 ;; DX allocated only on platforms with those additional VOPs.
1402 #!+raw-instance-init-vops
1403 (let* ((slot-values nil)
1404 (slot-specs
1405 (mapcan (lambda (dsd value)
1406 (unless (eq value '.do-not-initialize-slot.)
1407 (push value slot-values)
1408 (list (list* :slot (dsd-raw-type dsd) (dsd-index dsd)))))
1409 (dd-slots dd)
1410 values)))
1411 `(defun ,cons-name ,arglist
1412 ,@(when decls `((declare ,@decls)))
1413 (%make-structure-instance-macro ,dd ',slot-specs ,@(reverse slot-values))))
1414 #!-raw-instance-init-vops
1415 (let ((instance (gensym "INSTANCE")) slot-values slot-specs raw-slots raw-values)
1416 (mapc (lambda (dsd value)
1417 (unless (eq value '.do-not-initialize-slot.)
1418 (let ((raw-type (dsd-raw-type dsd)))
1419 (cond ((eq t raw-type)
1420 (push value slot-values)
1421 (push (list* :slot raw-type (dsd-index dsd)) slot-specs))
1423 (push value raw-values)
1424 (push dsd raw-slots))))))
1425 (dd-slots dd)
1426 values)
1427 `(defun ,cons-name ,arglist
1428 ,@(when decls`((declare ,@decls)))
1429 ,(if raw-slots
1430 `(let ((,instance (%make-structure-instance-macro ,dd ',slot-specs ,@slot-values)))
1431 ,@(mapcar (lambda (dsd value)
1432 ;; (Note that we can't in general use the
1433 ;; ordinary named slot setter function here
1434 ;; because the slot might be :READ-ONLY, so we
1435 ;; whip up new LAMBDA representations of slot
1436 ;; setters for the occasion.)
1437 `(,(slot-setter-lambda-form dd dsd) ,value ,instance))
1438 raw-slots
1439 raw-values)
1440 ,instance)
1441 `(%make-structure-instance-macro ,dd ',slot-specs ,@slot-values))))
1442 `(sfunction ,ftype-arglist ,(dd-name dd))))
1444 ;;; Create a default (non-BOA) keyword constructor.
1445 (defun create-keyword-constructor (defstruct creator)
1446 (declare (type function creator))
1447 (collect ((arglist (list '&key))
1448 (vals)
1449 (decls)
1450 (ftype-args))
1451 (let ((int-type (if (eq 'vector (dd-type defstruct))
1452 (dd-element-type defstruct)
1453 t)))
1454 (dolist (slot (dd-slots defstruct))
1455 (let* ((name (dsd-name slot))
1456 (dum (copy-symbol name))
1457 (keyword (keywordicate name))
1458 (specfied-type `(and ,int-type ,(dsd-type slot)))
1459 ;; Canonicalize the type for a prettier macro-expansion
1460 ;; but leave it as is if there is a conflict.
1461 (type (or (type-specifier (specifier-type specfied-type))
1462 specfied-type)))
1463 (arglist `((,keyword ,dum) ,(dsd-default slot)))
1464 (vals dum)
1465 ;; KLUDGE: we need a separate type declaration for for
1466 ;; keyword arguments, since default values bypass the
1467 ;; checking provided by the FTYPE.
1468 (unless (eq t type)
1469 (decls `(type ,type ,dum)))
1470 (ftype-args `(,keyword ,type)))))
1471 (funcall creator
1472 defstruct (dd-default-constructor defstruct)
1473 (arglist) `(&key ,@(ftype-args)) (decls) (vals))))
1475 ;;; Given a structure and a BOA constructor spec, call CREATOR with
1476 ;;; the appropriate args to make a constructor.
1477 (defun create-boa-constructor (defstruct boa creator)
1478 (declare (type function creator))
1479 (multiple-value-bind (llks req opt rest keys aux)
1480 (parse-lambda-list (second boa)
1481 :accept
1482 (lambda-list-keyword-mask
1483 '(&optional &rest &key &allow-other-keys &aux)))
1484 (collect ((arglist)
1485 (vars)
1486 (skipped-vars)
1487 (ftype-args)
1488 (decls))
1489 (let ((int-type (if (eq 'vector (dd-type defstruct))
1490 (dd-element-type defstruct)
1491 t)))
1492 (labels ((get-slot (name)
1493 (let* ((res (find name (dd-slots defstruct)
1494 :test #'string=
1495 :key #'dsd-name))
1496 (type (type-specifier
1497 (specifier-type
1498 `(and ,int-type ,(if res
1499 (dsd-type res)
1500 t))))))
1501 (values type (when res (dsd-default res)))))
1502 (do-default (arg &optional keyp)
1503 (multiple-value-bind (type default) (get-slot arg)
1504 (arglist `(,arg ,default))
1505 (vars arg)
1506 (if keyp
1507 (arg-type type (keywordicate arg) arg)
1508 (arg-type type))))
1509 (arg-type (type &optional key var)
1510 (cond (key
1511 ;; KLUDGE: see comment in CREATE-KEYWORD-CONSTRUCTOR.
1512 (unless (eq t type)
1513 (decls `(type ,type ,var)))
1514 (ftype-args `(,key ,type)))
1516 (ftype-args type)))))
1517 (dolist (arg req)
1518 (arglist arg)
1519 (vars arg)
1520 (arg-type (get-slot arg)))
1522 (when opt
1523 (arglist '&optional)
1524 (ftype-args '&optional)
1525 (dolist (arg opt)
1526 (cond ((consp arg)
1527 (destructuring-bind
1528 ;; FIXME: this shares some logic (though not
1529 ;; code) with the &key case below (and it
1530 ;; looks confusing) -- factor out the logic
1531 ;; if possible. - CSR, 2002-04-19
1532 (name
1533 &optional
1534 (def (nth-value 1 (get-slot name)))
1535 (supplied-test nil supplied-test-p))
1537 (arglist `(,name ,def ,@(if supplied-test-p `(,supplied-test) nil)))
1538 (vars name)
1539 (arg-type (get-slot name))
1540 (when supplied-test-p
1541 (vars supplied-test))))
1543 (do-default arg)))))
1545 (when rest
1546 (let ((rest (car rest)))
1547 (arglist '&rest rest)
1548 (vars rest)
1549 (ftype-args '&rest)
1550 (arg-type t)
1551 (decls `(type list ,rest))))
1553 (when (ll-kwds-keyp llks)
1554 (arglist '&key)
1555 (ftype-args '&key)
1556 (dolist (key keys)
1557 (if (consp key)
1558 (destructuring-bind (wot
1559 &optional
1560 (def nil def-p)
1561 (supplied-test nil supplied-test-p))
1563 (multiple-value-bind (key name)
1564 (if (consp wot)
1565 (destructuring-bind (key var) wot
1566 (values key var))
1567 (values (keywordicate wot) wot))
1568 (multiple-value-bind (type slot-def)
1569 (get-slot name)
1570 (arglist `(,wot ,(if def-p def slot-def)
1571 ,@(if supplied-test-p `(,supplied-test) nil)))
1572 (vars name)
1573 (arg-type type key name)
1574 (when supplied-test-p
1575 (vars supplied-test)))))
1576 (do-default key t))))
1578 (when (ll-kwds-allowp llks)
1579 (arglist '&allow-other-keys)
1580 (ftype-args '&allow-other-keys))
1582 ;; PARSE-LAMBDA-LIST doesn't distinguish between &AUX with nothing
1583 ;; after it, and absence of &AUX. They mean the same thing, even as
1584 ;; "interesting" as &AUX can be in a BOA lambda list [CLHS 3.4.6]
1585 (when aux
1586 (arglist '&aux)
1587 (dolist (arg aux)
1588 (typecase arg
1589 ((cons symbol cons)
1590 (let ((var (first arg)))
1591 (arglist arg)
1592 (vars var)
1593 (decls `(type ,(get-slot var) ,var))))
1595 ;; (&AUX X) and (&AUX (X)) both skip the slot
1596 (skipped-vars (if (consp arg) (first arg) arg))))))))
1598 (funcall creator defstruct (first boa)
1599 (arglist) (ftype-args) (decls)
1600 (loop for slot in (dd-slots defstruct)
1601 for name = (dsd-name slot)
1602 collect (cond ((find name (skipped-vars) :test #'string=)
1603 ;; CLHS 3.4.6 Boa Lambda Lists
1604 '.do-not-initialize-slot.)
1605 ((or (find (dsd-name slot) (vars) :test #'string=)
1606 (let ((type (dsd-type slot)))
1607 (if (eq t type)
1608 (dsd-default slot)
1609 `(the ,type ,(dsd-default slot))))))))))))
1611 ;;; Grovel the constructor options, and decide what constructors (if
1612 ;;; any) to create.
1613 (defun constructor-definitions (defstruct)
1614 (let ((no-constructors nil)
1615 (boas ())
1616 (defaults ())
1617 (creator (ecase (dd-type defstruct)
1618 (structure #'create-structure-constructor)
1619 (vector #'create-vector-constructor)
1620 (list #'create-list-constructor))))
1621 (dolist (constructor (dd-constructors defstruct))
1622 (destructuring-bind (name &optional (boa-ll nil boa-p)) constructor
1623 (declare (ignore boa-ll))
1624 (cond ((not name) (setq no-constructors t))
1625 (boa-p (push constructor boas))
1626 (t (push name defaults)))))
1628 (when no-constructors
1629 (when (or defaults boas)
1630 (error "(:CONSTRUCTOR NIL) combined with other :CONSTRUCTORs"))
1631 (return-from constructor-definitions ()))
1633 (unless (or defaults boas)
1634 (push (symbolicate "MAKE-" (dd-name defstruct)) defaults))
1636 (collect ((res))
1637 (when defaults
1638 (let ((cname (first defaults)))
1639 (setf (dd-default-constructor defstruct) cname)
1640 (multiple-value-bind (cons ftype)
1641 (create-keyword-constructor defstruct creator)
1642 (res `(declaim (ftype ,ftype ,@defaults)))
1643 (res cons))
1644 (dolist (other-name (rest defaults))
1645 (res `(setf (fdefinition ',other-name) (fdefinition ',cname))))))
1647 (dolist (boa boas)
1648 (multiple-value-bind (cons ftype)
1649 (create-boa-constructor defstruct boa creator)
1650 (res `(declaim (ftype ,ftype ,(first boa))))
1651 (res cons)))
1653 (res))))
1655 (defun accessor-definitions (dd)
1656 (loop for dsd in (dd-slots dd)
1657 for accessor-name = (dsd-accessor-name dsd)
1658 for place-form = (%accessor-place-form dd dsd `(the ,(dd-name dd) instance))
1659 unless (accessor-inherited-data accessor-name dd)
1660 collect
1661 `(defun ,accessor-name (instance)
1662 ,(cond ((not (dsd-type dsd))
1663 place-form)
1664 ((dsd-safe-p dsd)
1665 `(truly-the ,(dsd-type dsd) ,place-form))
1667 `(the ,(dsd-type dsd) ,place-form))))
1668 and unless (dsd-read-only dsd)
1669 collect
1670 `(defun (setf ,accessor-name) (value instance)
1671 (setf ,place-form (the ,(dsd-type dsd) value)))))
1673 (defun copier-definition (dd)
1674 (when (dd-copier-name dd)
1675 `(defun ,(dd-copier-name dd) (instance)
1676 (copy-structure (the ,(dd-name dd) instance)))))
1678 (defun predicate-definition (dd)
1679 (when (dd-predicate-name dd)
1680 `(defun ,(dd-predicate-name dd) (object)
1681 (typep object ',(dd-name dd)))))
1684 ;;;; instances with ALTERNATE-METACLASS
1685 ;;;;
1686 ;;;; The CMU CL support for structures with ALTERNATE-METACLASS was a
1687 ;;;; fairly general extension embedded in the main DEFSTRUCT code, and
1688 ;;;; the result was an fairly impressive mess as ALTERNATE-METACLASS
1689 ;;;; extension mixed with ANSI CL generality (e.g. :TYPE and :INCLUDE)
1690 ;;;; and CMU CL implementation hairiness (esp. raw slots). This SBCL
1691 ;;;; version is much less ambitious, noticing that ALTERNATE-METACLASS
1692 ;;;; is only used to implement CONDITION, STANDARD-INSTANCE, and
1693 ;;;; GENERIC-FUNCTION, and defining a simple specialized
1694 ;;;; separate-from-DEFSTRUCT macro to provide only enough
1695 ;;;; functionality to support those.
1696 ;;;;
1697 ;;;; KLUDGE: The defining macro here is so specialized that it's ugly
1698 ;;;; in its own way. It also violates once-and-only-once by knowing
1699 ;;;; much about structures and layouts that is already known by the
1700 ;;;; main DEFSTRUCT macro. Hopefully it will go away presently
1701 ;;;; (perhaps when CL:CLASS and SB-PCL:CLASS meet) as per FIXME below.
1702 ;;;; -- WHN 2001-10-28
1703 ;;;;
1704 ;;;; FIXME: There seems to be no good reason to shoehorn CONDITION,
1705 ;;;; STANDARD-INSTANCE, and GENERIC-FUNCTION into mutated structures
1706 ;;;; instead of just implementing them as primitive objects. (This
1707 ;;;; reduced-functionality macro seems pretty close to the
1708 ;;;; functionality of !DEFINE-PRIMITIVE-OBJECT..)
1710 ;;; The complete list of alternate-metaclass DEFSTRUCTs:
1711 ;;; CONDITION SB-EVAL:INTERPRETED-FUNCTION
1712 ;;; SB-PCL::STANDARD-INSTANCE SB-PCL::STANDARD-FUNCALLABLE-INSTANCE
1713 ;;; SB-PCL::CTOR SB-PCL::%METHOD-FUNCTION
1715 (defun make-dd-with-alternate-metaclass (&key (class-name (missing-arg))
1716 (superclass-name (missing-arg))
1717 (metaclass-name (missing-arg))
1718 (dd-type (missing-arg))
1719 metaclass-constructor
1720 slot-names)
1721 (let* ((dd (make-defstruct-description class-name))
1722 (conc-name (concatenate 'string (symbol-name class-name) "-"))
1723 (dd-slots (let ((reversed-result nil)
1724 ;; The index starts at 1 for ordinary named
1725 ;; slots because slot 0 is magical, used for
1726 ;; the LAYOUT in CONDITIONs and
1727 ;; FUNCALLABLE-INSTANCEs. (This is the same
1728 ;; in ordinary structures too: see (INCF
1729 ;; DD-LENGTH) in
1730 ;; PARSE-DEFSTRUCT-NAME-AND-OPTIONS).
1731 (index 1))
1732 (dolist (slot-name slot-names)
1733 (push (make-defstruct-slot-description
1734 :name slot-name
1735 :index index
1736 :accessor-name (symbolicate conc-name slot-name))
1737 reversed-result)
1738 (incf index))
1739 (nreverse reversed-result))))
1740 ;; We do *not* fill in the COPIER-NAME and PREDICATE-NAME
1741 ;; because none of the magical alternate-metaclass structures
1742 ;; have copiers and predicates that "Just work"
1743 (case dd-type
1744 ;; We don't support inheritance of alternate metaclass stuff,
1745 ;; and it's not a general-purpose facility, so sanity check our
1746 ;; own code.
1747 (structure
1748 (aver (eq superclass-name 't)))
1749 (funcallable-structure
1750 (aver (eq superclass-name 'function)))
1751 (t (bug "Unknown DD-TYPE in ALTERNATE-METACLASS: ~S" dd-type)))
1752 (setf (dd-alternate-metaclass dd) (list superclass-name
1753 metaclass-name
1754 metaclass-constructor)
1755 (dd-slots dd) dd-slots
1756 (dd-length dd) (1+ (length slot-names))
1757 (dd-type dd) dd-type)
1758 dd))
1760 ;;; make !DEFSTRUCT-WITH-ALTERNATE-METACLASS compilable by the host
1761 ;;; lisp, installing the information we need to reason about the
1762 ;;; structures (layouts and classoids).
1764 ;;; FIXME: we should share the parsing and the DD construction between
1765 ;;; this and the cross-compiler version, but my brain was too small to
1766 ;;; get that right. -- CSR, 2006-09-14
1767 #+sb-xc-host
1768 (defmacro !defstruct-with-alternate-metaclass
1769 (class-name &key
1770 (slot-names (missing-arg))
1771 (boa-constructor (missing-arg))
1772 (superclass-name (missing-arg))
1773 (metaclass-name (missing-arg))
1774 (metaclass-constructor (missing-arg))
1775 (dd-type (missing-arg))
1776 predicate
1777 (runtime-type-checks-p t))
1779 (declare (type (and list (not null)) slot-names))
1780 (declare (type (and symbol (not null))
1781 boa-constructor
1782 superclass-name
1783 metaclass-name
1784 metaclass-constructor))
1785 (declare (type symbol predicate))
1786 (declare (type (member structure funcallable-structure) dd-type))
1787 (declare (ignore boa-constructor predicate runtime-type-checks-p))
1789 (let* ((dd (make-dd-with-alternate-metaclass
1790 :class-name class-name
1791 :slot-names slot-names
1792 :superclass-name superclass-name
1793 :metaclass-name metaclass-name
1794 :metaclass-constructor metaclass-constructor
1795 :dd-type dd-type)))
1796 `(progn
1798 (eval-when (:compile-toplevel :load-toplevel :execute)
1799 (%compiler-set-up-layout ',dd ',(!inherits-for-structure dd))))))
1801 (sb!xc:proclaim '(special *defstruct-hooks*))
1803 (sb!xc:defmacro !defstruct-with-alternate-metaclass
1804 (class-name &key
1805 (slot-names (missing-arg))
1806 (boa-constructor (missing-arg))
1807 (superclass-name (missing-arg))
1808 (metaclass-name (missing-arg))
1809 (metaclass-constructor (missing-arg))
1810 (dd-type (missing-arg))
1811 predicate
1812 (runtime-type-checks-p t))
1814 (declare (type (and list (not null)) slot-names))
1815 (declare (type (and symbol (not null))
1816 boa-constructor
1817 superclass-name
1818 metaclass-name
1819 metaclass-constructor))
1820 (declare (type symbol predicate))
1821 (declare (type (member structure funcallable-structure) dd-type))
1823 (let* ((dd (make-dd-with-alternate-metaclass
1824 :class-name class-name
1825 :slot-names slot-names
1826 :superclass-name superclass-name
1827 :metaclass-name metaclass-name
1828 :metaclass-constructor metaclass-constructor
1829 :dd-type dd-type))
1830 (dd-slots (dd-slots dd))
1831 (dd-length (1+ (length slot-names)))
1832 (object-gensym (make-symbol "OBJECT"))
1833 (new-value-gensym (make-symbol "NEW-VALUE"))
1834 (delayed-layout-form `(%delayed-get-compiler-layout ,class-name)))
1835 (multiple-value-bind (raw-maker-form raw-reffer-operator)
1836 (ecase dd-type
1837 (structure
1838 (values `(%make-structure-instance-macro ,dd nil)
1839 '%instance-ref))
1840 (funcallable-structure
1841 (values `(let ((,object-gensym
1842 (%make-funcallable-instance ,dd-length)))
1843 (setf (%funcallable-instance-layout ,object-gensym)
1844 ,delayed-layout-form)
1845 ,object-gensym)
1846 '%funcallable-instance-info)))
1847 `(progn
1849 (eval-when (:compile-toplevel :load-toplevel :execute)
1850 (%compiler-set-up-layout ',dd ',(!inherits-for-structure dd)))
1852 ;; slot readers and writers
1853 (declaim (inline ,@(mapcar #'dsd-accessor-name dd-slots)))
1854 ,@(mapcar (lambda (dsd)
1855 `(defun ,(dsd-accessor-name dsd) (,object-gensym)
1856 ,@(when runtime-type-checks-p
1857 `((declare (type ,class-name ,object-gensym))))
1858 (,raw-reffer-operator ,object-gensym
1859 ,(dsd-index dsd))))
1860 dd-slots)
1861 (declaim (inline ,@(mapcar (lambda (dsd)
1862 `(setf ,(dsd-accessor-name dsd)))
1863 dd-slots)))
1864 ,@(mapcar (lambda (dsd)
1865 `(defun (setf ,(dsd-accessor-name dsd)) (,new-value-gensym
1866 ,object-gensym)
1867 ,@(when runtime-type-checks-p
1868 `((declare (type ,class-name ,object-gensym))))
1869 (setf (,raw-reffer-operator ,object-gensym
1870 ,(dsd-index dsd))
1871 ,new-value-gensym)))
1872 dd-slots)
1874 ;; constructor
1875 (defun ,boa-constructor ,slot-names
1876 (let ((,object-gensym ,raw-maker-form))
1877 ,@(mapcar (lambda (slot-name)
1878 (let ((dsd (or (find slot-name dd-slots
1879 :key #'dsd-name :test #'string=)
1880 (bug "Bogus alt-metaclass boa ctor"))))
1881 `(setf (,(dsd-accessor-name dsd) ,object-gensym)
1882 ,slot-name)))
1883 slot-names)
1884 ,object-gensym))
1886 ;; predicate
1887 ,@(when predicate
1888 ;; Just delegate to the compiler's type optimization
1889 ;; code, which knows how to generate inline type tests
1890 ;; for the whole CMU CL INSTANCE menagerie.
1891 `(defun ,predicate (,object-gensym)
1892 (typep ,object-gensym ',class-name)))
1894 ;; Usually we AVER instead of ASSERT, but one alternate-metaclass
1895 ;; structure definition is cross-compiled before AVER is a known macro.
1896 ;; It could be a def!macro perhaps, but ASSERT works just fine here
1897 ;; without adding to image size, since these toplevel forms
1898 ;; belong to code that is discarded after cold-init.
1899 (assert (null *defstruct-hooks*))))))
1901 ;;;; finalizing bootstrapping
1903 ;;; Set up DD and LAYOUT for STRUCTURE-OBJECT class itself.
1905 ;;; Ordinary structure classes effectively :INCLUDE STRUCTURE-OBJECT
1906 ;;; when they have no explicit :INCLUDEs, so (1) it needs to be set up
1907 ;;; before we can define ordinary structure classes, and (2) it's
1908 ;;; special enough (and simple enough) that we just build it by hand
1909 ;;; instead of trying to generalize the ordinary DEFSTRUCT code.
1910 (defun !set-up-structure-object-class ()
1911 (let ((dd (make-defstruct-description 'structure-object)))
1912 (setf
1913 (dd-slots dd) nil
1914 (dd-length dd) 1
1915 (dd-type dd) 'structure)
1916 (%compiler-set-up-layout dd)))
1917 #+sb-xc-host(!set-up-structure-object-class)
1919 ;;; early structure predeclarations: Set up DD and LAYOUT for ordinary
1920 ;;; (non-ALTERNATE-METACLASS) structures which are needed early.
1921 (dolist (args
1922 '#.(sb-cold:read-from-file
1923 "src/code/early-defstruct-args.lisp-expr"))
1924 (let* ((dd (parse-defstruct-name-and-options-and-slot-descriptions
1925 (first args)
1926 (rest args)))
1927 (inherits (!inherits-for-structure dd)))
1928 (%compiler-defstruct dd inherits)))
1930 (defun find-defstruct-description (name &optional (errorp t))
1931 (let* ((classoid (find-classoid name errorp))
1932 (info (and classoid
1933 (layout-info (classoid-layout classoid)))))
1934 (cond ((defstruct-description-p info)
1935 info)
1936 (errorp
1937 (error "No DEFSTRUCT-DESCRIPTION for ~S." name)))))
1939 (defun structure-instance-accessor-p (name)
1940 (let ((info (info :function :source-transform name)))
1941 (and (listp info)
1942 (defstruct-slot-description-p (cdr info))
1943 info)))
1945 ;;; These functions are required to emulate SBCL kernel functions
1946 ;;; in a vanilla ANSI Common Lisp cross-compilation host.
1947 ;;; The emulation doesn't need to be efficient, since it's needed
1948 ;;; only for object dumping.
1949 #+sb-xc-host
1950 (progn
1951 (defun xc-dumpable-structure-instance-p (x)
1952 (and (typep x 'cl:structure-object)
1953 (let ((name (type-of x)))
1954 ;; Don't allow totally random structures, only ones that the
1955 ;; cross-compiler has been advised will work.
1956 (and (get name :sb-xc-allow-dumping-instances)
1957 ;; but we must also have cross-compiled it for real.
1958 (sb!kernel::compiler-layout-ready-p name)
1959 ;; and I don't know anything about raw slots
1960 ;; Coincidentally, in either representation of
1961 ;; raw-slot-metadata, 0 represents no untagged slots.
1962 (zerop (layout-raw-slot-metadata
1963 (info :type :compiler-layout name)))))))
1964 (defun %instance-layout (instance)
1965 (aver (or (typep instance 'structure!object)
1966 (xc-dumpable-structure-instance-p instance)))
1967 (classoid-layout (find-classoid (type-of instance))))
1968 (defun %instance-length (instance)
1969 ;; INSTANCE-LENGTH tells you how many data words the backend is able to
1970 ;; physically access in this structure. Since every structure occupies
1971 ;; an even number of words, the storage slots comprise an odd number
1972 ;; of words after subtracting 1 for the header.
1973 ;; And in fact the fasl dumper / loader do write and read potentially
1974 ;; one cell beyond the instance's LAYOUT-LENGTH if it was not odd.
1975 ;; I'm not sure whether that is a good or bad thing.
1976 ;; But be that as it may, in the cross-compiler you must not access
1977 ;; more cells than there are in the declared structure because there
1978 ;; is no lower level storage that you can peek at.
1979 ;; So INSTANCE-LENGTH is exactly the same as LAYOUT-LENGTH on the host.
1980 (layout-length (%instance-layout instance)))
1981 (defun %instance-ref (instance index)
1982 (let ((layout (%instance-layout instance)))
1983 ;; with compact headers, 0 is an ordinary slot index.
1984 ;; without, it's the layout.
1985 (if (eql index (1- sb!vm:instance-data-start))
1986 (error "XC Host should use %INSTANCE-LAYOUT, not %INSTANCE-REF 0")
1987 (let* ((dd (layout-info layout))
1988 ;; If data starts at 1, then subtract 1 from index.
1989 ;; otherwise use the index as-is.
1990 (dsd (elt (dd-slots dd)
1991 (- index sb!vm:instance-data-start)))
1992 (accessor-name (dsd-accessor-name dsd)))
1993 ;; Why AVER these: because it is slightly abstraction-breaking
1994 ;; to assume that the slot-index N is the NTH item in the DSDs.
1995 ;; The target Lisp never assumes that.
1996 (aver (and (eql (dsd-index dsd) index) (eq (dsd-raw-type dsd) t)))
1997 (funcall accessor-name instance)))))
1998 ;; Setting with (FUNCALL `(SETF ,accessor) ...) is unportable because
1999 ;; "The mechanism by which defstruct arranges for slot accessors to be
2000 ;; usable with setf is implementation-dependent; for example, it may
2001 ;; use setf functions, setf expanders, or some other
2002 ;; implementation-dependent mechanism ..."
2003 ;; But such capability seems not to be needed.
2004 (defun %instance-set (instance index new-value)
2005 (declare (ignore instance index new-value))
2006 (error "Can not use %INSTANCE-SET on cross-compilation host.")))
2008 (/show0 "code/defstruct.lisp end of file")