0.7.1.3:
[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
137 ;;; service function for structure constructors
138 (defun %make-instance-with-layout (layout)
139   (let ((result (%make-instance (layout-length layout))))
140     (setf (%instance-layout result) layout)
141     result))
142 \f
143 ;;;; target-only parts of the DEFSTRUCT top level code
144
145 ;;; Catch attempts to mess up definitions of symbols in the CL package.
146 (defun protect-cl (symbol)
147   (/show0 "entering PROTECT-CL, SYMBOL=..")
148   (/hexstr symbol)
149   (when (and *cold-init-complete-p*
150              (eq (symbol-package symbol) *cl-package*))
151     (cerror "Go ahead and patch the system."
152             "attempting to modify a symbol in the COMMON-LISP package: ~S"
153             symbol))
154   (/show0 "leaving PROTECT-CL")
155   (values))
156
157 ;;; the part of %DEFSTRUCT which makes sense only on the target SBCL
158 ;;;
159 ;;; (The "static" in the name is because it needs to be done not only
160 ;;; in ordinary toplevel %DEFSTRUCT, but also in cold init as early as
161 ;;; possible, to simulate static linking of structure functions as
162 ;;; nearly as possible.)
163 (defun %target-defstruct (dd layout)
164   (declare (type defstruct-description dd))
165   (declare (type layout layout))
166
167   (/show0 "entering %TARGET-DEFSTRUCT")
168
169   (remhash (dd-name dd) *typecheckfuns*)
170
171   ;; (Constructors aren't set up here, because constructors are
172   ;; varied enough (possibly parsing any specified argument list)
173   ;; that we can't reasonably implement them as closures, so we
174   ;; implement them with DEFUN instead.)
175
176   ;; Set FDEFINITIONs for slot accessors.
177   (dolist (dsd (dd-slots dd))
178     (/show0 "doing FDEFINITION for slot accessor")
179     (let ((accessor-name (dsd-accessor-name dsd)))
180       (/show0 "ACCESSOR-NAME=..")
181       (/hexstr accessor-name)
182       (protect-cl accessor-name)
183       (/hexstr "getting READER-FUN and WRITER-FUN")
184       (multiple-value-bind (reader-fun writer-fun) (slot-accessor-funs dd dsd)
185         (declare (type function reader-fun writer-fun))
186         (/show0 "got READER-FUN and WRITER-FUN=..")
187         (/hexstr reader-fun)
188         (setf (symbol-function accessor-name) reader-fun)
189         (unless (dsd-read-only dsd)
190           (/show0 "setting FDEFINITION for WRITER-FUN=..")
191           (/hexstr writer-fun)
192           (setf (fdefinition `(setf ,accessor-name)) writer-fun)))))
193
194   ;; Set FDEFINITION for copier.
195   (when (dd-copier-name dd)
196     (/show0 "doing FDEFINITION for copier")
197     (protect-cl (dd-copier-name dd))
198     ;; We can't use COPY-STRUCTURE for other kinds of objects, notably
199     ;; funcallable structures, since it returns a STRUCTURE-OBJECT.
200     ;; (And funcallable instances don't need copiers anyway.)
201     (aver (eql (dd-type dd) 'structure))
202     (setf (symbol-function (dd-copier-name dd))
203           ;; FIXME: should use a closure which checks arg type before copying
204           #'copy-structure))
205
206   ;; Set FDEFINITION for predicate.
207   (when (dd-predicate-name dd)
208     (/show0 "doing FDEFINITION for predicate")
209     (protect-cl (dd-predicate-name dd))
210     (setf (symbol-function (dd-predicate-name dd))
211           (ecase (dd-type dd)
212             ;; structures with LAYOUTs
213             ((structure funcallable-structure)
214              (/show0 "with-LAYOUT case")
215              (lambda (object)
216                (declare (optimize (speed 3) (safety 0)))
217                (/noshow0 "in with-LAYOUT structure predicate closure, OBJECT,LAYOUT=..")
218                (/nohexstr object)
219                (/nohexstr layout)
220                (typep-to-layout object layout)))
221             ;; structures with no LAYOUT (i.e. :TYPE VECTOR or :TYPE LIST)
222             ;;
223             ;; FIXME: should handle the :NAMED T case in these cases
224             (vector
225              (/show0 ":TYPE VECTOR case")
226              #'vectorp)
227             (list
228              (/show0 ":TYPE LIST case")
229              #'listp))))
230
231   (when (dd-doc dd)
232     (setf (fdocumentation (dd-name dd) 'type)
233           (dd-doc dd)))
234
235   (/show0 "leaving %TARGET-DEFSTRUCT")
236   (values))
237 \f
238 ;;;; generating out-of-line slot accessor functions
239
240 ;;; FIXME: Ideally, the presence of the type checks in the functions
241 ;;; here would be conditional on the optimization policy at the point
242 ;;; of expansion of DEFSTRUCT. (For now we're just doing the simpler
243 ;;; thing, putting in the type checks unconditionally.)
244
245 ;;; Return (VALUES SLOT-READER-FUN SLOT-WRITER-FUN).
246 (defun slot-accessor-funs (dd dsd)
247
248   #+sb-xc (/show0 "entering SLOT-ACCESSOR-FUNS")
249
250   ;; various code generators
251   ;;
252   ;; Note: They're only minimally parameterized, and cavalierly grab
253   ;; things like INSTANCE and DSD-INDEX from the namespace they're
254   ;; expanded in.
255   (macrolet (;; code shared between funcallable instance case and the
256              ;; ordinary STRUCTURE-OBJECT case: Handle native
257              ;; structures with LAYOUTs and (possibly) raw slots.
258              (%native-slot-accessor-funs (dd-ref-fun-name)
259                (let ((instance-type-check-form
260                       '(%check-structure-type-from-layout instance layout)))
261                  (/show "macroexpanding %NATIVE-SLOT-ACCESSOR-FUNS" dd-ref-fun-name instance-type-check-form)
262                  `(let ((layout (dd-layout-or-lose dd))
263                         (dsd-raw-type (dsd-raw-type dsd)))
264                     #+sb-xc (/show0 "in %NATIVE-SLOT-ACCESSOR-FUNS macroexpanded code")
265                     ;; Map over all the possible RAW-TYPEs, compiling
266                     ;; a different closure function for each one, so
267                     ;; that once the COND over RAW-TYPEs happens (at
268                     ;; the time closure is allocated) there are no
269                     ;; more decisions to be made and things execute
270                     ;; reasonably efficiently.
271                     (cond
272                      ;; nonraw slot case
273                      ((eql dsd-raw-type t)
274                       #+sb-xc (/show0 "in nonraw slot case")
275                       (%slotplace-accessor-funs
276                        (,dd-ref-fun-name instance dsd-index)
277                        ,instance-type-check-form))
278                      ;; raw slot cases
279                      ,@(mapcar (lambda (rtd)
280                                  (let ((raw-type (raw-slot-data-raw-type rtd))
281                                        (accessor-name
282                                         (raw-slot-data-accessor-name rtd))
283                                        (n-words (raw-slot-data-n-words rtd)))
284                                    `((equal dsd-raw-type ',raw-type)
285                                      #+sb-xc (/show0 "in raw slot case")
286                                      (let ((raw-index (dd-raw-index dd)))
287                                        (multiple-value-bind (scaled-dsd-index
288                                                              misalignment)
289                                            (floor dsd-index ,n-words)
290                                          (aver (zerop misalignment))
291                                          (%slotplace-accessor-funs
292                                           (,accessor-name (,dd-ref-fun-name
293                                                            instance
294                                                            raw-index)
295                                                           scaled-dsd-index)
296                                           ,instance-type-check-form))))))
297                                *raw-slot-data-list*)
298                      ;; oops
299                      (t
300                       (bug "unexpected DSD-RAW-TYPE ~S" dsd-raw-type))))))
301              ;; code shared between DEFSTRUCT :TYPE LIST and
302              ;; DEFSTRUCT :TYPE VECTOR cases: Handle the "typed
303              ;; structure" case, with no LAYOUTs and no raw slots.
304              (%colontyped-slot-accessor-funs () (error "stub")) 
305              ;; the common structure of the raw-slot and not-raw-slot
306              ;; cases, defined in terms of the writable SLOTPLACE. All
307              ;; possible flavors of slot access should be able to pass
308              ;; through here.
309              (%slotplace-accessor-funs (slotplace instance-type-check-form)
310                (/show "macroexpanding %SLOTPLACE-ACCESSOR-FUNS" slotplace instance-type-check-form)
311                `(values (lambda (instance)
312                           (/noshow0 "in %SLOTPLACE-ACCESSOR-FUNS-defined reader")
313                           ,instance-type-check-form
314                           (/noshow0 "back from INSTANCE-TYPE-CHECK-FORM")
315                           ,slotplace)
316                         (let ((typecheckfun (typespec-typecheckfun dsd-type)))
317                           (lambda (new-value instance)
318                             (/noshow0 "in %SLOTPLACE-ACCESSOR-FUNS-defined writer")
319                             ,instance-type-check-form
320                             (/noshow0 "back from INSTANCE-TYPE-CHECK-FORM")
321                             (funcall typecheckfun new-value)
322                             (/noshow0 "back from TYPECHECKFUN")
323                             (setf ,slotplace new-value))))))
324
325     (let ((dsd-index (dsd-index dsd))
326           (dsd-type (dsd-type dsd)))
327             
328       #+sb-xc (/show0 "got DSD-TYPE=..")
329       #+sb-xc (/hexstr dsd-type)
330       (ecase (dd-type dd)
331
332         ;; native structures
333         (structure
334          #+sb-xc (/show0 "case of DSD-TYPE = STRUCTURE")
335          (%native-slot-accessor-funs %instance-ref))
336                                      
337         ;; structures with the :TYPE option
338
339         ;; FIXME: Worry about these later..
340         #|
341         ;; In :TYPE LIST and :TYPE VECTOR structures, ANSI specifies the
342         ;; layout completely, so that raw slots are impossible.
343         (list
344          (dd-type-slot-accessor-funs nth-but-with-sane-arg-order
345                                  `(%check-structure-type-from-dd
346                                  :maybe-raw-p nil))
347         (vector
348          (dd-type-slot-accessor-funs aref
349                                  :maybe-raw-p nil)))
350         |#
351         ))))
352 \f
353 ;;; Copy any old kind of structure.
354 (defun copy-structure (structure)
355   #!+sb-doc
356   "Return a copy of STRUCTURE with the same (EQL) slot values."
357   (declare (type structure-object structure))
358   (let* ((len (%instance-length structure))
359          (res (%make-instance len))
360          (layout (%instance-layout structure)))
361
362     (declare (type index len))
363     (when (layout-invalid layout)
364       (error "attempt to copy an obsolete structure:~%  ~S" structure))
365
366     ;; Copy ordinary slots.
367     (dotimes (i len)
368       (declare (type index i))
369       (setf (%instance-ref res i)
370             (%instance-ref structure i)))
371
372     ;; Copy raw slots.
373     (let ((raw-index (dd-raw-index (layout-info layout))))
374       (when raw-index
375         (let* ((data (%instance-ref structure raw-index))
376                (raw-len (length data))
377                (new (make-array raw-len :element-type '(unsigned-byte 32))))
378           (declare (type (simple-array (unsigned-byte 32) (*)) data))
379           (setf (%instance-ref res raw-index) new)
380           (dotimes (i raw-len)
381             (setf (aref new i) (aref data i))))))
382
383     res))
384 \f
385 ;;; default PRINT-OBJECT and MAKE-LOAD-FORM methods
386
387 (defun %default-structure-pretty-print (structure stream)
388   (let* ((layout (%instance-layout structure))
389          (name (sb!xc:class-name (layout-class layout)))
390          (dd (layout-info layout)))
391     (pprint-logical-block (stream nil :prefix "#S(" :suffix ")")
392       (prin1 name stream)
393       (let ((remaining-slots (dd-slots dd)))
394         (when remaining-slots
395           (write-char #\space stream)
396           ;; CMU CL had (PPRINT-INDENT :BLOCK 2 STREAM) here,
397           ;; but I can't see why. -- WHN 20000205
398           (pprint-newline :linear stream)
399           (loop
400            (pprint-pop)
401            (let ((slot (pop remaining-slots)))
402              (write-char #\: stream)
403              (output-symbol-name (dsd-%name slot) stream)
404              (write-char #\space stream)
405              (pprint-newline :miser stream)
406              (output-object (funcall (fdefinition (dsd-accessor-name slot))
407                                      structure)
408                             stream)
409              (when (null remaining-slots)
410                (return))
411              (write-char #\space stream)
412              (pprint-newline :linear stream))))))))
413 (defun %default-structure-ugly-print (structure stream)
414   (let* ((layout (%instance-layout structure))
415          (name (sb!xc:class-name (layout-class layout)))
416          (dd (layout-info layout)))
417     (descend-into (stream)
418       (write-string "#S(" stream)
419       (prin1 name stream)
420       (do ((index 0 (1+ index))
421            (remaining-slots (dd-slots dd) (cdr remaining-slots)))
422           ((or (null remaining-slots)
423                (and (not *print-readably*)
424                     *print-length*
425                     (>= index *print-length*)))
426            (if (null remaining-slots)
427                (write-string ")" stream)
428                (write-string " ...)" stream)))
429         (declare (type index index))
430         (write-char #\space stream)
431         (write-char #\: stream)
432         (let ((slot (first remaining-slots)))
433           (output-symbol-name (dsd-%name slot) stream)
434           (write-char #\space stream)
435           (output-object
436            (funcall (fdefinition (dsd-accessor-name slot))
437                     structure)
438            stream))))))
439 (defun default-structure-print (structure stream depth)
440   (declare (ignore depth))
441   (cond ((funcallable-instance-p structure)
442          (print-unreadable-object (structure stream :identity t :type t)))
443         (*print-pretty*
444          (%default-structure-pretty-print structure stream))
445         (t
446          (%default-structure-ugly-print structure stream))))
447 (def!method print-object ((x structure-object) stream)
448   (default-structure-print x stream *current-level-in-print*))
449
450 (defun make-load-form-saving-slots (object &key slot-names environment)
451   (declare (ignore object environment))
452   (if slot-names
453       (error "stub: MAKE-LOAD-FORM-SAVING-SLOTS :SLOT-NAMES not implemented") ; KLUDGE
454       :just-dump-it-normally))
455 \f
456 ;;;; testing structure types
457
458 ;;; Return true if OBJ is an object of the structure type
459 ;;; corresponding to LAYOUT. This is called by the accessor closures,
460 ;;; which have a handle on the type's LAYOUT.
461 ;;;
462 ;;; FIXME: This is fairly big, so it should probably become
463 ;;; MAYBE-INLINE instead of INLINE, or its inlineness should become
464 ;;; conditional (probably through DEFTRANSFORM) on (> SPEED SPACE). Or
465 ;;; else we could fix things up so that the things which call it are
466 ;;; all closures, so that it's expanded only in a small number of
467 ;;; places.
468 #!-sb-fluid (declaim (inline typep-to-layout))
469 (defun typep-to-layout (obj layout)
470   (declare (type layout layout) (optimize (speed 3) (safety 0)))
471   (/noshow0 "entering TYPEP-TO-LAYOUT, OBJ,LAYOUT=..")
472   (/nohexstr obj)
473   (/nohexstr layout)
474   (when (layout-invalid layout)
475     (error "An obsolete structure accessor function was called."))
476   (/noshow0 "back from testing LAYOUT-INVALID LAYOUT")
477   ;; FIXME: CMU CL used (%INSTANCEP OBJ) here. Check that
478   ;; (TYPEP OBJ 'INSTANCE) is optimized to equally efficient code.
479   (and (typep obj 'instance)
480        (let ((obj-layout (%instance-layout obj)))
481          (cond ((eq obj-layout layout)
482                 ;; (In this case OBJ-LAYOUT can't be invalid, because
483                 ;; we determined LAYOUT is valid in the test above.)
484                 (/noshow0 "EQ case")
485                 t)
486                ((layout-invalid obj-layout)
487                 (/noshow0 "LAYOUT-INVALID case")
488                 (error 'layout-invalid
489                        :expected-type (layout-class obj-layout)
490                        :datum obj))
491                (t
492                 (let ((depthoid (layout-depthoid layout)))
493                   (/noshow0 "DEPTHOID case, DEPTHOID,LAYOUT-INHERITS=..")
494                   (/nohexstr depthoid)
495                   (/nohexstr layout-inherits)
496                   (and (> (layout-depthoid obj-layout) depthoid)
497                        (eq (svref (layout-inherits obj-layout) depthoid)
498                            layout))))))))
499 \f
500 ;;;; checking structure types
501
502 ;;; Check that X is an instance of the named structure type.
503 (defmacro %check-structure-type-from-name (x name)
504   `(%check-structure-type-from-layout ,x ,(compiler-layout-or-lose name)))
505
506 ;;; Check that X is a structure of the type described by DD.
507 (defmacro %check-structure-type-from-dd (x dd)
508   (declare (type defstruct-description dd))
509   (let ((class-name (dd-name dd)))
510     (ecase (dd-type dd)
511       ((structure funcallable-instance)
512        `(%check-structure-type-from-layout
513          ,x
514          ,(compiler-layout-or-lose class-name)))
515       ((vector)
516        (let ((xx (gensym "X")))
517          `(let ((,xx ,x))
518             (declare (type vector ,xx))
519             ,@(when (dd-named dd)
520                 `((unless (eql (aref ,xx 0) ',class-name)
521                     (error
522                      'simple-type-error
523                      :datum (aref ,xx 0)
524                      :expected-type `(member ,class-name)
525                      :format-control
526                      "~@<missing name in instance of ~
527                       VECTOR-typed structure ~S: ~2I~_S~:>"
528                      :format-arguments (list ',class-name ,xx)))))
529             (values))))
530       ((list)
531        (let ((xx (gensym "X")))
532          `(let ((,xx ,x))
533             (declare (type list ,xx))
534             ,@(when (dd-named dd)
535                 `((unless (eql (first ,xx) ',class-name)
536                     (error
537                      'simple-type-error
538                      :datum (aref ,xx 0)
539                      :expected-type `(member ,class-name)
540                      :format-control
541                      "~@<missing name in instance of LIST-typed structure ~S: ~
542                       ~2I~_S~:>"
543                      :format-arguments (list ',class-name ,xx)))))
544             (values)))))))
545
546 ;;; Check that X is an instance of the structure class with layout LAYOUT.
547 (defun %check-structure-type-from-layout (x layout)
548   (unless (typep-to-layout x layout)
549     (error 'type-error
550            :datum x
551            :expected-type (class-name (layout-class layout))))
552   (values))
553 \f
554 (/show0 "target-defstruct.lisp end of file")