0.pre7.81:
[sbcl.git] / src / code / target-defstruct.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB!KERNEL")
11
12 (/show0 "target-defstruct.lisp 12")
13 \f
14 ;;;; structure frobbing primitives
15
16 ;;; Allocate a new instance with LENGTH data slots.
17 (defun %make-instance (length)
18   (declare (type index length))
19   (%make-instance length))
20
21 ;;; Given an instance, return its length.
22 (defun %instance-length (instance)
23   (declare (type instance instance))
24   (%instance-length instance))
25
26 ;;; Return the value from the INDEXth slot of INSTANCE. This is SETFable.
27 (defun %instance-ref (instance index)
28   (%instance-ref instance index))
29
30 ;;; Set the INDEXth slot of INSTANCE to NEW-VALUE.
31 (defun %instance-set (instance index new-value)
32   (setf (%instance-ref instance index) new-value))
33
34 (defun %raw-ref-single (vec index)
35   (declare (type index index))
36   (%raw-ref-single vec index))
37
38 (defun %raw-ref-double (vec index)
39   (declare (type index index))
40   (%raw-ref-double vec index))
41
42 #!+long-float
43 (defun %raw-ref-long (vec index)
44   (declare (type index index))
45   (%raw-ref-long vec index))
46
47 (defun %raw-set-single (vec index val)
48   (declare (type index index))
49   (%raw-set-single vec index val))
50
51 (defun %raw-set-double (vec index val)
52   (declare (type index index))
53   (%raw-set-double vec index val))
54
55 #!+long-float
56 (defun %raw-set-long (vec index val)
57   (declare (type index index))
58   (%raw-set-long vec index val))
59
60 (defun %raw-ref-complex-single (vec index)
61   (declare (type index index))
62   (%raw-ref-complex-single vec index))
63
64 (defun %raw-ref-complex-double (vec index)
65   (declare (type index index))
66   (%raw-ref-complex-double vec index))
67
68 #!+long-float
69 (defun %raw-ref-complex-long (vec index)
70   (declare (type index index))
71   (%raw-ref-complex-long vec index))
72
73 (defun %raw-set-complex-single (vec index val)
74   (declare (type index index))
75   (%raw-set-complex-single vec index val))
76
77 (defun %raw-set-complex-double (vec index val)
78   (declare (type index index))
79   (%raw-set-complex-double vec index val))
80
81 #!+long-float
82 (defun %raw-set-complex-long (vec index val)
83   (declare (type index index))
84   (%raw-set-complex-long vec index val))
85
86 (defun %instance-layout (instance)
87   (%instance-layout instance))
88
89 (defun %set-instance-layout (instance new-value)
90   (%set-instance-layout instance new-value))
91
92 (defun %make-funcallable-instance (len layout)
93    (%make-funcallable-instance len layout))
94
95 (defun funcallable-instance-p (x) (funcallable-instance-p x))
96
97 (defun %funcallable-instance-info (fin i)
98   (%funcallable-instance-info fin i))
99
100 (defun %set-funcallable-instance-info (fin i new-value)
101   (%set-funcallable-instance-info fin i new-value))
102
103 (defun funcallable-instance-fun (fin)
104   (%funcallable-instance-lexenv fin))
105
106 ;;; The heart of the magic of funcallable instances ("FINs"). The
107 ;;; function for a FIN must be a magical INSTANCE-LAMBDA form. When
108 ;;; called (as with any other function), we grab the code pointer, and
109 ;;; call it, leaving the original function object in LEXENV (in case
110 ;;; it was a closure). If it is actually a FIN, then we need to do an
111 ;;; extra indirection with funcallable-instance-lexenv to get at any
112 ;;; closure environment. This extra indirection is set up when
113 ;;; accessing the closure environment of an INSTANCE-LAMBDA. Note that
114 ;;; the original FIN pointer is lost, so if the called function wants
115 ;;; to get at the original object to do some slot accesses, it must
116 ;;; close over the FIN object.
117 ;;;
118 ;;; If we set the FIN function to be a FIN, we directly copy across
119 ;;; both the code pointer and the lexenv, since that code pointer (for
120 ;;; an instance-lambda) is expecting that lexenv to be accessed. This
121 ;;; effectively pre-flattens what would otherwise be a chain of
122 ;;; indirections. (That used to happen when PCL dispatch functions
123 ;;; were byte-compiled; now that the byte compiler is gone, I can't
124 ;;; think of another example offhand. -- WHN 2001-10-06)
125 ;;;
126 ;;; The only loss is that if someone accesses the
127 ;;; FUNCALLABLE-INSTANCE-FUN, then won't get a FIN back. This probably
128 ;;; doesn't matter, since PCL only sets the FIN function.
129 (defun (setf funcallable-instance-fun) (new-value fin)
130   (setf (%funcallable-instance-fun fin)
131         (%closure-fun new-value))
132   (setf (%funcallable-instance-lexenv fin)
133         (if (funcallable-instance-p new-value)
134             (%funcallable-instance-lexenv new-value)
135             new-value)))
136 \f
137 ;;;; target-only parts of the DEFSTRUCT top-level code
138
139 ;;; Catch attempts to mess up definitions of symbols in the CL package.
140 (defun protect-cl (symbol)
141   (/show0 "entering PROTECT-CL, SYMBOL=..")
142   (/hexstr symbol)
143   (when (and *cold-init-complete-p*
144              (eq (symbol-package symbol) *cl-package*))
145     (cerror "Go ahead and patch the system."
146             "attempting to modify a symbol in the COMMON-LISP package: ~S"
147             symbol))
148   (/show0 "leaving PROTECT-CL")
149   (values))
150
151 ;;; the part of %DEFSTRUCT which makes sense only on the target SBCL
152 ;;;
153 ;;; (The "static" in the name is because it needs to be done not only
154 ;;; in ordinary toplevel %DEFSTRUCT, but also in cold init as early as
155 ;;; possible, to simulate static linking of structure functions as
156 ;;; nearly as possible.)
157 (defun %target-defstruct (dd layout)
158   (declare (type defstruct-description dd))
159   (declare (type layout layout))
160
161   (/show0 "entering %TARGET-DEFSTRUCT")
162
163   (remhash (dd-name dd) *typecheckfuns*)
164
165   ;; (Constructors aren't set up here, because constructors are
166   ;; varied enough (possibly parsing any specified argument list)
167   ;; that we can't reasonably implement them as closures, so we
168   ;; implement them with DEFUN instead.)
169
170   ;; Set FDEFINITIONs for slot accessors.
171   (dolist (dsd (dd-slots dd))
172     (/show0 "doing FDEFINITION for slot accessor")
173     (let ((accessor-name (dsd-accessor-name dsd)))
174       (/show0 "ACCESSOR-NAME=..")
175       (/hexstr accessor-name)
176       (protect-cl accessor-name)
177       (/hexstr "getting READER-FUN and WRITER-FUN")
178       (multiple-value-bind (reader-fun writer-fun) (slot-accessor-funs dd dsd)
179         (declare (type function reader-fun writer-fun))
180         (/show0 "got READER-FUN and WRITER-FUN=..")
181         (/hexstr reader-fun)
182         (setf (symbol-function accessor-name) reader-fun)
183         (unless (dsd-read-only dsd)
184           (/show0 "setting FDEFINITION for WRITER-FUN=..")
185           (/hexstr writer-fun)
186           (setf (fdefinition `(setf ,accessor-name)) writer-fun)))))
187
188   ;; Set FDEFINITION for copier.
189   (when (dd-copier-name dd)
190     (/show0 "doing FDEFINITION for copier")
191     (protect-cl (dd-copier-name dd))
192     ;; We can't use COPY-STRUCTURE for other kinds of objects, notably
193     ;; funcallable structures, since it returns a STRUCTURE-OBJECT.
194     ;; (And funcallable instances don't need copiers anyway.)
195     (aver (eql (dd-type dd) 'structure))
196     (setf (symbol-function (dd-copier-name dd))
197           ;; FIXME: should use a closure which checks arg type before copying
198           #'copy-structure))
199
200   ;; Set FDEFINITION for predicate.
201   (when (dd-predicate-name dd)
202     (/show0 "doing FDEFINITION for predicate")
203     (protect-cl (dd-predicate-name dd))
204     (setf (symbol-function (dd-predicate-name dd))
205           (ecase (dd-type dd)
206             ;; structures with LAYOUTs
207             ((structure funcallable-structure)
208              (/show0 "with-LAYOUT case")
209              (lambda (object)
210                (declare (optimize (speed 3) (safety 0)))
211                (/noshow0 "in with-LAYOUT structure predicate closure, OBJECT,LAYOUT=..")
212                (/nohexstr object)
213                (/nohexstr layout)
214                (typep-to-layout object layout)))
215             ;; structures with no LAYOUT (i.e. :TYPE VECTOR or :TYPE LIST)
216             ;;
217             ;; FIXME: should handle the :NAMED T case in these cases
218             (vector
219              (/show0 ":TYPE VECTOR case")
220              #'vectorp)
221             (list
222              (/show0 ":TYPE LIST case")
223              #'listp))))
224
225   (when (dd-doc dd)
226     (setf (fdocumentation (dd-name dd) 'type)
227           (dd-doc dd)))
228
229   (/show0 "leaving %TARGET-DEFSTRUCT")
230   (values))
231 \f
232 ;;;; generating out-of-line slot accessor functions
233
234 ;;; FIXME: Ideally, the presence of the type checks in the functions
235 ;;; here would be conditional on the optimization policy at the point
236 ;;; of expansion of DEFSTRUCT. (For now we're just doing the simpler
237 ;;; thing, putting in the type checks unconditionally.)
238
239 ;;; Return (VALUES SLOT-READER-FUN SLOT-WRITER-FUN).
240 (defun slot-accessor-funs (dd dsd)
241
242   #+sb-xc (/show0 "entering SLOT-ACCESSOR-FUNS")
243
244   ;; various code generators
245   ;;
246   ;; Note: They're only minimally parameterized, and cavalierly grab
247   ;; things like INSTANCE and DSD-INDEX from the namespace they're
248   ;; expanded in.
249   (macrolet (;; code shared between funcallable instance case and the
250              ;; ordinary STRUCTURE-OBJECT case: Handle native
251              ;; structures with LAYOUTs and (possibly) raw slots.
252              (%native-slot-accessor-funs (dd-ref-fun-name)
253                (let ((instance-type-check-form
254                       '(%check-structure-type-from-layout instance layout)))
255                  (/show "macroexpanding %NATIVE-SLOT-ACCESSOR-FUNS" dd-ref-fun-name instance-type-check-form)
256                  `(let ((layout (dd-layout-or-lose dd))
257                         (dsd-raw-type (dsd-raw-type dsd)))
258                     #+sb-xc (/show0 "in %NATIVE-SLOT-ACCESSOR-FUNS macroexpanded code")
259                     ;; Map over all the possible RAW-TYPEs, compiling
260                     ;; a different closure-function for each one, so
261                     ;; that once the COND over RAW-TYPEs happens (at
262                     ;; the time closure is allocated) there are no
263                     ;; more decisions to be made and things execute
264                     ;; reasonably efficiently.
265                     (cond
266                      ;; nonraw slot case
267                      ((eql dsd-raw-type t)
268                       #+sb-xc (/show0 "in nonraw slot case")
269                       (%slotplace-accessor-funs
270                        (,dd-ref-fun-name instance dsd-index)
271                        ,instance-type-check-form))
272                      ;; raw slot cases
273                      ,@(mapcar (lambda (rtd)
274                                  (let ((raw-type (raw-slot-data-raw-type rtd))
275                                        (accessor-name
276                                         (raw-slot-data-accessor-name rtd))
277                                        (n-words (raw-slot-data-n-words rtd)))
278                                    `((equal dsd-raw-type ',raw-type)
279                                      #+sb-xc (/show0 "in raw slot case")
280                                      (let ((raw-index (dd-raw-index dd)))
281                                        (multiple-value-bind (scaled-dsd-index
282                                                              misalignment)
283                                            (floor dsd-index ,n-words)
284                                          (aver (zerop misalignment))
285                                          (%slotplace-accessor-funs
286                                           (,accessor-name (,dd-ref-fun-name
287                                                            instance
288                                                            raw-index)
289                                                           scaled-dsd-index)
290                                           ,instance-type-check-form))))))
291                                *raw-slot-data-list*)
292                      ;; oops
293                      (t
294                       (error "internal error: unexpected DSD-RAW-TYPE ~S"
295                              dsd-raw-type))))))
296              ;; code shared between DEFSTRUCT :TYPE LIST and
297              ;; DEFSTRUCT :TYPE VECTOR cases: Handle the "typed
298              ;; structure" case, with no LAYOUTs and no raw slots.
299              (%colontyped-slot-accessor-funs () (error "stub")) 
300              ;; the common structure of the raw-slot and not-raw-slot
301              ;; cases, defined in terms of the writable SLOTPLACE. All
302              ;; possible flavors of slot access should be able to pass
303              ;; through here.
304              (%slotplace-accessor-funs (slotplace instance-type-check-form)
305                (/show "macroexpanding %SLOTPLACE-ACCESSOR-FUNS" slotplace instance-type-check-form)
306                `(values (lambda (instance)
307                           (/noshow0 "in %SLOTPLACE-ACCESSOR-FUNS-defined reader")
308                           ,instance-type-check-form
309                           (/noshow0 "back from INSTANCE-TYPE-CHECK-FORM")
310                           ,slotplace)
311                         (let ((typecheckfun (typespec-typecheckfun dsd-type)))
312                           (lambda (new-value instance)
313                             (/noshow0 "in %SLOTPLACE-ACCESSOR-FUNS-defined writer")
314                             ,instance-type-check-form
315                             (/noshow0 "back from INSTANCE-TYPE-CHECK-FORM")
316                             (funcall typecheckfun new-value)
317                             (/noshow0 "back from TYPECHECKFUN")
318                             (setf ,slotplace new-value))))))
319
320     (let ((dsd-index (dsd-index dsd))
321           (dsd-type (dsd-type dsd)))
322             
323       #+sb-xc (/show0 "got DSD-TYPE=..")
324       #+sb-xc (/hexstr dsd-type)
325       (ecase (dd-type dd)
326
327         ;; native structures
328         (structure
329          #+sb-xc (/show0 "case of DSD-TYPE = STRUCTURE")
330          (%native-slot-accessor-funs %instance-ref))
331                                      
332         ;; structures with the :TYPE option
333
334         ;; FIXME: Worry about these later..
335         #|
336         ;; In :TYPE LIST and :TYPE VECTOR structures, ANSI specifies the
337         ;; layout completely, so that raw slots are impossible.
338         (list
339          (dd-type-slot-accessor-funs nth-but-with-sane-arg-order
340                                  `(%check-structure-type-from-dd
341                                  :maybe-raw-p nil))
342         (vector
343          (dd-type-slot-accessor-funs aref
344                                  :maybe-raw-p nil)))
345         |#
346         ))))
347 \f
348 ;;; Copy any old kind of structure.
349 (defun copy-structure (structure)
350   #!+sb-doc
351   "Return a copy of STRUCTURE with the same (EQL) slot values."
352   (declare (type structure-object structure))
353   (let* ((len (%instance-length structure))
354          (res (%make-instance len))
355          (layout (%instance-layout structure)))
356
357     (declare (type index len))
358     (when (layout-invalid layout)
359       (error "attempt to copy an obsolete structure:~%  ~S" structure))
360
361     ;; Copy ordinary slots.
362     (dotimes (i len)
363       (declare (type index i))
364       (setf (%instance-ref res i)
365             (%instance-ref structure i)))
366
367     ;; Copy raw slots.
368     (let ((raw-index (dd-raw-index (layout-info layout))))
369       (when raw-index
370         (let* ((data (%instance-ref structure raw-index))
371                (raw-len (length data))
372                (new (make-array raw-len :element-type '(unsigned-byte 32))))
373           (declare (type (simple-array (unsigned-byte 32) (*)) data))
374           (setf (%instance-ref res raw-index) new)
375           (dotimes (i raw-len)
376             (setf (aref new i) (aref data i))))))
377
378     res))
379 \f
380 ;;; default PRINT-OBJECT and MAKE-LOAD-FORM methods
381
382 (defun %default-structure-pretty-print (structure stream)
383   (let* ((layout (%instance-layout structure))
384          (name (sb!xc:class-name (layout-class layout)))
385          (dd (layout-info layout)))
386     (pprint-logical-block (stream nil :prefix "#S(" :suffix ")")
387       (prin1 name stream)
388       (let ((remaining-slots (dd-slots dd)))
389         (when remaining-slots
390           (write-char #\space stream)
391           ;; CMU CL had (PPRINT-INDENT :BLOCK 2 STREAM) here,
392           ;; but I can't see why. -- WHN 20000205
393           (pprint-newline :linear stream)
394           (loop
395            (pprint-pop)
396            (let ((slot (pop remaining-slots)))
397              (write-char #\: stream)
398              (output-symbol-name (dsd-%name slot) stream)
399              (write-char #\space stream)
400              (pprint-newline :miser stream)
401              (output-object (funcall (fdefinition (dsd-accessor-name slot))
402                                      structure)
403                             stream)
404              (when (null remaining-slots)
405                (return))
406              (write-char #\space stream)
407              (pprint-newline :linear stream))))))))
408 (defun %default-structure-ugly-print (structure stream)
409   (let* ((layout (%instance-layout structure))
410          (name (sb!xc:class-name (layout-class layout)))
411          (dd (layout-info layout)))
412     (descend-into (stream)
413       (write-string "#S(" stream)
414       (prin1 name stream)
415       (do ((index 0 (1+ index))
416            (remaining-slots (dd-slots dd) (cdr remaining-slots)))
417           ((or (null remaining-slots)
418                (and (not *print-readably*)
419                     *print-length*
420                     (>= index *print-length*)))
421            (if (null remaining-slots)
422                (write-string ")" stream)
423                (write-string " ...)" stream)))
424         (declare (type index index))
425         (write-char #\space stream)
426         (write-char #\: stream)
427         (let ((slot (first remaining-slots)))
428           (output-symbol-name (dsd-%name slot) stream)
429           (write-char #\space stream)
430           (output-object
431            (funcall (fdefinition (dsd-accessor-name slot))
432                     structure)
433            stream))))))
434 (defun default-structure-print (structure stream depth)
435   (declare (ignore depth))
436   (cond ((funcallable-instance-p structure)
437          (print-unreadable-object (structure stream :identity t :type t)))
438         (*print-pretty*
439          (%default-structure-pretty-print structure stream))
440         (t
441          (%default-structure-ugly-print structure-stream))))
442 (def!method print-object ((x structure-object) stream)
443   (default-structure-print x stream *current-level*))
444
445 (defun make-load-form-saving-slots (object &key slot-names environment)
446   (declare (ignore object environment))
447   (if slot-names
448     (error "stub: MAKE-LOAD-FORM-SAVING-SLOTS :SLOT-NAMES not implemented") ; KLUDGE
449     :just-dump-it-normally))
450 \f
451 ;;;; testing structure types
452
453 ;;; Return true if OBJ is an object of the structure type
454 ;;; corresponding to LAYOUT. This is called by the accessor closures,
455 ;;; which have a handle on the type's LAYOUT.
456 ;;;
457 ;;; FIXME: This is fairly big, so it should probably become
458 ;;; MAYBE-INLINE instead of INLINE. Or else we could fix things up so
459 ;;; that the things which call it are all closures, so that it's
460 ;;; expanded only in a small number of places.
461 #!-sb-fluid (declaim (inline typep-to-layout))
462 (defun typep-to-layout (obj layout)
463   (declare (type layout layout) (optimize (speed 3) (safety 0)))
464   (/noshow0 "entering TYPEP-TO-LAYOUT, OBJ,LAYOUT=..")
465   (/nohexstr obj)
466   (/nohexstr layout)
467   (when (layout-invalid layout)
468     (error "An obsolete structure accessor function was called."))
469   (/noshow0 "back from testing LAYOUT-INVALID LAYOUT")
470   ;; FIXME: CMU CL used (%INSTANCEP OBJ) here. Check that
471   ;; (TYPEP OBJ 'INSTANCE) is optimized to equally efficient code.
472   (and (typep obj 'instance)
473        (let ((obj-layout (%instance-layout obj)))
474          (cond ((eq obj-layout layout)
475                 ;; (In this case OBJ-LAYOUT can't be invalid, because
476                 ;; we determined LAYOUT is valid in the test above.)
477                 (/noshow0 "EQ case")
478                 t)
479                ((layout-invalid obj-layout)
480                 (/noshow0 "LAYOUT-INVALID case")
481                 (error 'layout-invalid
482                        :expected-type (layout-class obj-layout)
483                        :datum obj))
484                (t
485                 (let ((depthoid (layout-depthoid layout)))
486                   (/noshow0 "DEPTHOID case, DEPTHOID,LAYOUT-INHERITS=..")
487                   (/nohexstr depthoid)
488                   (/nohexstr layout-inherits)
489                   (and (> (layout-depthoid obj-layout) depthoid)
490                        (eq (svref (layout-inherits obj-layout) depthoid)
491                            layout))))))))
492 \f
493 ;;;; checking structure types
494
495 ;;; Check that X is an instance of the named structure type.
496 (defmacro %check-structure-type-from-name (x name)
497   `(%check-structure-type-from-layout ,x ,(compiler-layout-or-lose name)))
498
499 ;;; Check that X is a structure of the type described by DD.
500 (defmacro %check-structure-type-from-dd (x dd)
501   (declare (type defstruct-description dd))
502   (let ((class-name (dd-name dd)))
503     (ecase (dd-type dd)
504       ((structure funcallable-instance)
505        `(%check-structure-type-from-layout
506          ,x
507          ,(compiler-layout-or-lose class-name)))
508       ((vector)
509        (let ((xx (gensym "X")))
510          `(let ((,xx ,x))
511             (declare (type vector ,xx))
512             ,@(when (dd-named dd)
513                 `((unless (eql (aref ,xx 0) ',class-name)
514                     (error
515                      'simple-type-error
516                      :datum (aref ,xx 0)
517                      :expected-type `(member ,class-name)
518                      :format-control
519                      "~@<missing name in instance of ~
520                       VECTOR-typed structure ~S: ~2I~_S~:>"
521                      :format-arguments (list ',class-name ,xx)))))
522             (values))))
523       ((list)
524        (let ((xx (gensym "X")))
525          `(let ((,xx ,x))
526             (declare (type list ,xx))
527             ,@(when (dd-named dd)
528                 `((unless (eql (first ,xx) ',class-name)
529                     (error
530                      'simple-type-error
531                      :datum (aref ,xx 0)
532                      :expected-type `(member ,class-name)
533                      :format-control
534                      "~@<missing name in instance of LIST-typed structure ~S: ~
535                       ~2I~_S~:>"
536                      :format-arguments (list ',class-name ,xx)))))
537             (values)))))))
538
539 ;;; Check that X is an instance of the structure class with layout LAYOUT.
540 (defun %check-structure-type-from-layout (x layout)
541   (unless (typep-to-layout x layout)
542     (error 'type-error
543            :datum x
544            :expected-type (class-name (layout-class layout))))
545   (values))
546 \f
547 (/show0 "target-defstruct.lisp end of file")