0.pre7.74:
[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 sets up out-of-line implementations
152 ;;; of those structure functions which are sufficiently similar
153 ;;; between structures that they can be closures
154 ;;;
155 ;;; (The "static" in the name is because it needs to be done not only
156 ;;; in ordinary toplevel %DEFSTRUCT, but also in cold init as early as
157 ;;; possible, to simulate static linking of structure functions as
158 ;;; nearly as possible.)
159 (defun %target-defstruct (dd layout)
160   (declare (type defstruct-description dd))
161   (declare (type layout layout))
162
163   (/show0 "entering %TARGET-DEFSTRUCT")
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, and so
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   (/show0 "leaving %TARGET-DEFSTRUCT")
226   (values))
227 \f
228 ;;; Copy any old kind of structure.
229 (defun copy-structure (structure)
230   #!+sb-doc
231   "Return a copy of STRUCTURE with the same (EQL) slot values."
232   (declare (type structure-object structure))
233   (let* ((len (%instance-length structure))
234          (res (%make-instance len))
235          (layout (%instance-layout structure)))
236
237     (declare (type index len))
238     (when (layout-invalid layout)
239       (error "attempt to copy an obsolete structure:~%  ~S" structure))
240
241     ;; Copy ordinary slots.
242     (dotimes (i len)
243       (declare (type index i))
244       (setf (%instance-ref res i)
245             (%instance-ref structure i)))
246
247     ;; Copy raw slots.
248     (let ((raw-index (dd-raw-index (layout-info layout))))
249       (when raw-index
250         (let* ((data (%instance-ref structure raw-index))
251                (raw-len (length data))
252                (new (make-array raw-len :element-type '(unsigned-byte 32))))
253           (declare (type (simple-array (unsigned-byte 32) (*)) data))
254           (setf (%instance-ref res raw-index) new)
255           (dotimes (i raw-len)
256             (setf (aref new i) (aref data i))))))
257
258     res))
259 \f
260 ;;; default PRINT-OBJECT and MAKE-LOAD-FORM methods
261
262 (defun %default-structure-pretty-print (structure stream)
263   (let* ((layout (%instance-layout structure))
264          (name (sb!xc:class-name (layout-class layout)))
265          (dd (layout-info layout)))
266     (pprint-logical-block (stream nil :prefix "#S(" :suffix ")")
267       (prin1 name stream)
268       (let ((remaining-slots (dd-slots dd)))
269         (when remaining-slots
270           (write-char #\space stream)
271           ;; CMU CL had (PPRINT-INDENT :BLOCK 2 STREAM) here,
272           ;; but I can't see why. -- WHN 20000205
273           (pprint-newline :linear stream)
274           (loop
275            (pprint-pop)
276            (let ((slot (pop remaining-slots)))
277              (write-char #\: stream)
278              (output-symbol-name (dsd-%name slot) stream)
279              (write-char #\space stream)
280              (pprint-newline :miser stream)
281              (output-object (funcall (fdefinition (dsd-accessor-name slot))
282                                      structure)
283                             stream)
284              (when (null remaining-slots)
285                (return))
286              (write-char #\space stream)
287              (pprint-newline :linear stream))))))))
288 (defun %default-structure-ugly-print (structure stream)
289   (let* ((layout (%instance-layout structure))
290          (name (sb!xc:class-name (layout-class layout)))
291          (dd (layout-info layout)))
292     (descend-into (stream)
293       (write-string "#S(" stream)
294       (prin1 name stream)
295       (do ((index 0 (1+ index))
296            (remaining-slots (dd-slots dd) (cdr remaining-slots)))
297           ((or (null remaining-slots)
298                (and (not *print-readably*)
299                     *print-length*
300                     (>= index *print-length*)))
301            (if (null remaining-slots)
302                (write-string ")" stream)
303                (write-string " ...)" stream)))
304         (declare (type index index))
305         (write-char #\space stream)
306         (write-char #\: stream)
307         (let ((slot (first remaining-slots)))
308           (output-symbol-name (dsd-%name slot) stream)
309           (write-char #\space stream)
310           (output-object
311            (funcall (fdefinition (dsd-accessor-name slot))
312                     structure)
313            stream))))))
314 (defun default-structure-print (structure stream depth)
315   (declare (ignore depth))
316   (cond ((funcallable-instance-p structure)
317          (print-unreadable-object (structure stream :identity t :type t)))
318         (*print-pretty*
319          (%default-structure-pretty-print structure stream))
320         (t
321          (%default-structure-ugly-print structure-stream))))
322 (def!method print-object ((x structure-object) stream)
323   (default-structure-print x stream *current-level*))
324
325 (defun make-load-form-saving-slots (object &key slot-names environment)
326   (declare (ignore object environment))
327   (if slot-names
328     (error "stub: MAKE-LOAD-FORM-SAVING-SLOTS :SLOT-NAMES not implemented") ; KLUDGE
329     :just-dump-it-normally))
330 \f
331 ;;;; testing structure types
332
333 ;;; Return true if OBJ is an object of the structure type
334 ;;; corresponding to LAYOUT. This is called by the accessor closures,
335 ;;; which have a handle on the type's LAYOUT.
336 ;;;
337 ;;; FIXME: This is fairly big, so it should probably become
338 ;;; MAYBE-INLINE instead of INLINE. Or else we could fix things up so
339 ;;; that the things which call it are all closures, so that it's
340 ;;; expanded only in a small number of places.
341 #!-sb-fluid (declaim (inline typep-to-layout))
342 (defun typep-to-layout (obj layout)
343   (declare (type layout layout) (optimize (speed 3) (safety 0)))
344   (/noshow0 "entering TYPEP-TO-LAYOUT, OBJ,LAYOUT=..")
345   (/nohexstr obj)
346   (/nohexstr layout)
347   (when (layout-invalid layout)
348     (error "An obsolete structure accessor function was called."))
349   (/noshow0 "back from testing LAYOUT-INVALID LAYOUT")
350   ;; FIXME: CMU CL used (%INSTANCEP OBJ) here. Check that
351   ;; (TYPEP OBJ 'INSTANCE) is optimized to equally efficient code.
352   (and (typep obj 'instance)
353        (let ((obj-layout (%instance-layout obj)))
354          (cond ((eq obj-layout layout)
355                 ;; (In this case OBJ-LAYOUT can't be invalid, because
356                 ;; we determined LAYOUT is valid in the test above.)
357                 (/noshow0 "EQ case")
358                 t)
359                ((layout-invalid obj-layout)
360                 (/noshow0 "LAYOUT-INVALID case")
361                 (error 'layout-invalid
362                        :expected-type (layout-class obj-layout)
363                        :datum obj))
364                (t
365                 (let ((depthoid (layout-depthoid layout)))
366                   (/noshow0 "DEPTHOID case, DEPTHOID,LAYOUT-INHERITS=..")
367                   (/nohexstr depthoid)
368                   (/nohexstr layout-inherits)
369                   (and (> (layout-depthoid obj-layout) depthoid)
370                        (eq (svref (layout-inherits obj-layout) depthoid)
371                            layout))))))))
372 \f
373 ;;;; checking structure types
374
375 ;;; Check that X is an instance of the named structure type.
376 (defmacro %check-structure-type-from-name (x name)
377   `(%check-structure-type-from-layout ,x ,(compiler-layout-or-lose name)))
378
379 ;;; Check that X is a structure of the type described by DD.
380 (defmacro %check-structure-type-from-dd (x dd)
381   (declare (type defstruct-description dd))
382   (let ((class-name (dd-name dd)))
383     (ecase (dd-type dd)
384       ((structure funcallable-instance)
385        `(%check-structure-type-from-layout
386          ,x
387          ,(compiler-layout-or-lose class-name)))
388       ((vector)
389        (let ((xx (gensym "X")))
390          `(let ((,xx ,x))
391             (declare (type vector ,xx))
392             ,@(when (dd-named dd)
393                 `((unless (eql (aref ,xx 0) ',class-name)
394                     (error
395                      'simple-type-error
396                      :datum (aref ,xx 0)
397                      :expected-type `(member ,class-name)
398                      :format-control
399                      "~@<missing name in instance of ~
400                       VECTOR-typed structure ~S: ~2I~_S~:>"
401                      :format-arguments (list ',class-name ,xx)))))
402             (values))))
403       ((list)
404        (let ((xx (gensym "X")))
405          `(let ((,xx ,x))
406             (declare (type list ,xx))
407             ,@(when (dd-named dd)
408                 `((unless (eql (first ,xx) ',class-name)
409                     (error
410                      'simple-type-error
411                      :datum (aref ,xx 0)
412                      :expected-type `(member ,class-name)
413                      :format-control
414                      "~@<missing name in instance of LIST-typed structure ~S: ~
415                       ~2I~_S~:>"
416                      :format-arguments (list ',class-name ,xx)))))
417             (values)))))))
418
419 ;;; Check that X is an instance of the structure class with layout LAYOUT.
420 (defun %check-structure-type-from-layout (x layout)
421   (unless (typep-to-layout x layout)
422     (error 'type-error
423            :datum x
424            :expected-type (class-name (layout-class layout))))
425   (values))
426 \f
427 (/show0 "target-defstruct.lisp end of file")