handle non-standard slot allocations when updating classes
[sbcl.git] / src / pcl / low.lisp
1 ;;;; This file contains portable versions of low-level functions and macros
2 ;;;; which are ripe for implementation specific customization. None of the code
3 ;;;; in this file *has* to be customized for a particular Common Lisp
4 ;;;; implementation. Moreover, in some implementations it may not make any
5 ;;;; sense to customize some of this code.
6 ;;;;
7 ;;;; The original version was intended to support portable customization to
8 ;;;; lotso different Lisp implementations. This functionality is gone in the
9 ;;;; current version, and it now runs only under SBCL. (Now that ANSI Common
10 ;;;; Lisp has mixed CLOS into the insides of the system (e.g. error handling
11 ;;;; and printing) so deeply that it's not very meaningful to bootstrap Common
12 ;;;; Lisp without CLOS, the old functionality is of dubious use. -- WHN
13 ;;;; 19981108)
14
15 ;;;; This software is part of the SBCL system. See the README file for more
16 ;;;; information.
17
18 ;;;; This software is derived from software originally released by Xerox
19 ;;;; Corporation. Copyright and release statements follow. Later modifications
20 ;;;; to the software are in the public domain and are provided with
21 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
22 ;;;; information.
23
24 ;;;; copyright information from original PCL sources:
25 ;;;;
26 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
27 ;;;; All rights reserved.
28 ;;;;
29 ;;;; Use and copying of this software and preparation of derivative works based
30 ;;;; upon this software are permitted. Any distribution of this software or
31 ;;;; derivative works must comply with all applicable United States export
32 ;;;; control laws.
33 ;;;;
34 ;;;; This software is made available AS IS, and Xerox Corporation makes no
35 ;;;; warranty about the software, its performance or its conformity to any
36 ;;;; specification.
37
38 (in-package "SB-PCL")
39 \f
40 (eval-when (:compile-toplevel :load-toplevel :execute)
41 (defvar *optimize-speed*
42   '(optimize (speed 3) (safety 0)))
43 ) ; EVAL-WHEN
44
45 (defmacro dotimes-fixnum ((var count &optional (result nil)) &body body)
46   `(dotimes (,var (the fixnum ,count) ,result)
47      (declare (fixnum ,var))
48      ,@body))
49
50 (declaim (inline random-fixnum))
51 (defun random-fixnum ()
52   (random (1+ most-positive-fixnum)))
53
54 (defconstant n-fixnum-bits #.(integer-length most-positive-fixnum))
55
56 ;;; Lambda which executes its body (or not) randomly. Used to drop
57 ;;; random cache entries.
58 (defmacro randomly-punting-lambda (lambda-list &body body)
59   (with-unique-names (drops drop-pos)
60     `(let ((,drops (random-fixnum))
61            (,drop-pos n-fixnum-bits))
62        (declare (fixnum ,drops)
63                 (type (integer 0 #.n-fixnum-bits) ,drop-pos))
64        (lambda ,lambda-list
65          (when (logbitp (the unsigned-byte (decf ,drop-pos)) ,drops)
66            (locally ,@body))
67          (when (zerop ,drop-pos)
68            (setf ,drops (random-fixnum)
69                  ,drop-pos n-fixnum-bits))))))
70 \f
71 ;;;; early definition of WRAPPER
72 ;;;;
73 ;;;; Most WRAPPER stuff is defined later, but the DEFSTRUCT itself
74 ;;;; is here early so that things like (TYPEP .. 'WRAPPER) can be
75 ;;;; compiled efficiently.
76
77 ;;; Note that for SBCL, as for CMU CL, the WRAPPER of a built-in or
78 ;;; structure class will be some other kind of SB-KERNEL:LAYOUT, but
79 ;;; this shouldn't matter, since the only two slots that WRAPPER adds
80 ;;; are meaningless in those cases.
81 (defstruct (wrapper
82             (:include layout
83                       ;; KLUDGE: In CMU CL, the initialization default
84                       ;; for LAYOUT-INVALID was NIL. In SBCL, that has
85                       ;; changed to :UNINITIALIZED, but PCL code might
86                       ;; still expect NIL for the initialization
87                       ;; default of WRAPPER-INVALID. Instead of trying
88                       ;; to find out, I just overrode the LAYOUT
89                       ;; default here. -- WHN 19991204
90                       (invalid nil)
91                       ;; This allows quick testing of wrapperness.
92                       (for-std-class-p t))
93             (:constructor make-wrapper-internal)
94             (:copier nil))
95   (slots () :type list))
96 #-sb-fluid (declaim (sb-ext:freeze-type wrapper))
97 \f
98 ;;;; PCL's view of funcallable instances
99
100 (!defstruct-with-alternate-metaclass standard-funcallable-instance
101   ;; KLUDGE: Note that neither of these slots is ever accessed by its
102   ;; accessor name as of sbcl-0.pre7.63. Presumably everything works
103   ;; by puns based on absolute locations. Fun fun fun.. -- WHN 2001-10-30
104   :slot-names (clos-slots name hash-code)
105   :boa-constructor %make-standard-funcallable-instance
106   :superclass-name function
107   :metaclass-name standard-classoid
108   :metaclass-constructor make-standard-classoid
109   :dd-type funcallable-structure
110   ;; Only internal implementation code will access these, and these
111   ;; accesses (slot readers in particular) could easily be a
112   ;; bottleneck, so it seems reasonable to suppress runtime type
113   ;; checks.
114   ;;
115   ;; (Except note KLUDGE above that these accessors aren't used at all
116   ;; (!) as of sbcl-0.pre7.63, so for now it's academic.)
117   :runtime-type-checks-p nil)
118
119 (import 'sb-kernel:funcallable-instance-p)
120
121 (defun set-funcallable-instance-function (fin new-value)
122   (declare (type function new-value))
123   (aver (funcallable-instance-p fin))
124   (setf (funcallable-instance-fun fin) new-value))
125
126 ;;; FIXME: these macros should just go away.  It's not clear whether
127 ;;; the inline functions defined by
128 ;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS are as efficient as they could
129 ;;; be; ordinary defstruct accessors are defined as source transforms.
130 (defun fsc-instance-p (fin)
131   (funcallable-instance-p fin))
132 (define-compiler-macro fsc-instance-p (fin)
133   `(funcallable-instance-p ,fin))
134 (defmacro fsc-instance-wrapper (fin)
135   `(%funcallable-instance-layout ,fin))
136 (defmacro fsc-instance-slots (fin)
137   `(%funcallable-instance-info ,fin 1))
138 (defmacro fsc-instance-hash (fin)
139   `(%funcallable-instance-info ,fin 3))
140 \f
141 (declaim (inline clos-slots-ref (setf clos-slots-ref)))
142 (declaim (ftype (function (simple-vector index) t) clos-slots-ref))
143 (defun clos-slots-ref (slots index)
144   (svref slots index))
145 (declaim (ftype (function (t simple-vector index) t) (setf clos-slots-ref)))
146 (defun (setf clos-slots-ref) (new-value slots index)
147   (setf (svref slots index) new-value))
148
149 ;;; Note on implementation under CMU CL >=17 and SBCL: STD-INSTANCE-P
150 ;;; is only used to discriminate between functions (including FINs)
151 ;;; and normal instances, so we can return true on structures also. A
152 ;;; few uses of (OR STD-INSTANCE-P FSC-INSTANCE-P) are changed to
153 ;;; PCL-INSTANCE-P.
154 (defun std-instance-p (x)
155   (%instancep x))
156 (define-compiler-macro std-instance-p (x)
157   `(%instancep ,x))
158
159 ;; a temporary definition used for debugging the bootstrap
160 #+sb-show
161 (defun print-std-instance (instance stream depth)
162   (declare (ignore depth))
163   (print-unreadable-object (instance stream :type t :identity t)
164     (let ((class (class-of instance)))
165       (when (or (eq class (find-class 'standard-class nil))
166                 (eq class (find-class 'funcallable-standard-class nil))
167                 (eq class (find-class 'built-in-class nil)))
168         (princ (early-class-name instance) stream)))))
169
170 ;;; This is the value that we stick into a slot to tell us that it is
171 ;;; unbound. It may seem gross, but for performance reasons, we make
172 ;;; this an interned symbol. That means that the fast check to see
173 ;;; whether a slot is unbound is to say (EQ <val> '..SLOT-UNBOUND..).
174 ;;; That is considerably faster than looking at the value of a special
175 ;;; variable.
176 ;;;
177 ;;; It seems only reasonable to also export this for users, since
178 ;;; otherwise dealing with STANDARD-INSTANCE-ACCESS becomes harder
179 ;;; -- and slower -- than it needs to be.
180 (defconstant +slot-unbound+ '..slot-unbound..
181   "SBCL specific extentions to MOP: if this value is read from an
182 instance using STANDARD-INSTANCE-ACCESS, the slot is unbound.
183 Similarly, an :INSTANCE allocated slot can be made unbound by
184 assigning this to it using (SETF STANDARD-INSTANCE-ACCESS).
185
186 Value of +SLOT-UNBOUND+ is unspecified, and should not be relied to be
187 of any particular type, but it is guaranteed to be suitable for EQ
188 comparison.")
189
190 (defmacro %allocate-static-slot-storage--class (no-of-slots)
191   `(make-array ,no-of-slots :initial-element +slot-unbound+))
192
193 (defmacro std-instance-class (instance)
194   `(wrapper-class* (std-instance-wrapper ,instance)))
195 \f
196 ;;; When given a funcallable instance, SET-FUN-NAME *must* side-effect
197 ;;; that FIN to give it the name. When given any other kind of
198 ;;; function SET-FUN-NAME is allowed to return a new function which is
199 ;;; "the same" except that it has the name.
200 ;;;
201 ;;; In all cases, SET-FUN-NAME must return the new (or same)
202 ;;; function. (Unlike other functions to set stuff, it does not return
203 ;;; the new value.)
204 (defun set-fun-name (fun new-name)
205   #+sb-doc
206   "Set the name of a compiled function object. Return the function."
207   (when (valid-function-name-p fun)
208     (setq fun (fdefinition fun)))
209   (typecase fun
210     (%method-function (setf (%method-function-name fun) new-name))
211     #+sb-eval
212     (sb-eval:interpreted-function
213      (setf (sb-eval:interpreted-function-name fun) new-name))
214     (funcallable-instance ;; KLUDGE: probably a generic function...
215      (cond ((if (eq **boot-state** 'complete)
216                 (typep fun 'generic-function)
217                 (eq (class-of fun) *the-class-standard-generic-function*))
218             (setf (%funcallable-instance-info fun 2) new-name))
219            (t
220             (bug "unanticipated function type")))))
221   ;; Fixup name-to-function mappings in cases where the function
222   ;; hasn't been defined by DEFUN.  (FIXME: is this right?  This logic
223   ;; comes from CMUCL).  -- CSR, 2004-12-31
224   (when (and (consp new-name)
225              (member (car new-name) '(slow-method fast-method slot-accessor)))
226     (setf (fdefinition new-name) fun))
227   fun)
228 \f
229 ;;; FIXME: probably no longer needed after init
230 (defmacro precompile-random-code-segments (&optional system)
231   `(progn
232      (eval-when (:compile-toplevel)
233        (update-dispatch-dfuns))
234      (precompile-function-generators ,system)
235      (precompile-dfun-constructors ,system)
236      (precompile-ctors)))
237 \f
238 ;;; This definition is for interpreted code.
239 (defun pcl-instance-p (x)
240   (typep (layout-of x) 'wrapper))
241
242 ;;; CMU CL comment:
243 ;;;   We define this as STANDARD-INSTANCE, since we're going to
244 ;;;   clobber the layout with some standard-instance layout as soon as
245 ;;;   we make it, and we want the accessor to still be type-correct.
246 #|
247 (defstruct (standard-instance
248             (:predicate nil)
249             (:constructor %%allocate-instance--class ())
250             (:copier nil)
251             (:alternate-metaclass instance
252                                   cl:standard-class
253                                   make-standard-class))
254   (slots nil))
255 |#
256 (!defstruct-with-alternate-metaclass standard-instance
257   :slot-names (slots hash-code)
258   :boa-constructor %make-standard-instance
259   :superclass-name t
260   :metaclass-name standard-classoid
261   :metaclass-constructor make-standard-classoid
262   :dd-type structure
263   :runtime-type-checks-p nil)
264
265 ;;; Both of these operations "work" on structures, which allows the above
266 ;;; weakening of STD-INSTANCE-P.
267 (defmacro std-instance-slots (x) `(%instance-ref ,x 1))
268 (defmacro std-instance-wrapper (x) `(%instance-layout ,x))
269 ;;; KLUDGE: This one doesn't "work" on structures.  However, we
270 ;;; ensure, in SXHASH and friends, never to call it on structures.
271 (defmacro std-instance-hash (x) `(%instance-ref ,x 2))
272
273 ;;; FIXME: These functions are called every place we do a
274 ;;; CALL-NEXT-METHOD, and probably other places too. It's likely worth
275 ;;; selectively optimizing them with DEFTRANSFORMs and stuff, rather
276 ;;; than just indiscriminately expanding them inline everywhere.
277 (declaim (inline get-slots get-slots-or-nil))
278 (declaim (ftype (function (t) simple-vector) get-slots))
279 (declaim (ftype (function (t) (or simple-vector null)) get-slots-or-nil))
280 (defun get-slots (instance)
281   (if (std-instance-p instance)
282       (std-instance-slots instance)
283       (fsc-instance-slots instance)))
284 (defun get-slots-or-nil (instance)
285   ;; Suppress a code-deletion note.  FIXME: doing the FIXME above,
286   ;; integrating PCL more with the compiler, would remove the need for
287   ;; this icky stuff.
288   (declare (optimize (inhibit-warnings 3)))
289   (when (pcl-instance-p instance)
290     (get-slots instance)))
291
292 (defmacro get-wrapper (inst)
293   (once-only ((wrapper `(wrapper-of ,inst)))
294     `(progn
295        (aver (typep ,wrapper 'wrapper))
296        ,wrapper)))
297
298 ;;; FIXME: could be an inline function or ordinary function (like many
299 ;;; other things around here)
300 (defmacro get-instance-wrapper-or-nil (inst)
301   (once-only ((wrapper `(wrapper-of ,inst)))
302     `(if (typep ,wrapper 'wrapper)
303          ,wrapper
304          nil)))
305 \f
306 ;;;; support for useful hashing of PCL instances
307
308 (defvar *instance-hash-code-random-state* (make-random-state))
309 (defun get-instance-hash-code ()
310   ;; ANSI SXHASH wants us to make a good-faith effort to produce
311   ;; hash-codes that are well distributed within the range of
312   ;; non-negative fixnums, and this RANDOM operation does that, unlike
313   ;; the sbcl<=0.8.16 implementation of this operation as
314   ;; (INCF COUNTER).
315   ;;
316   ;; Hopefully there was no virtue to the old counter implementation
317   ;; that I am insufficiently insightful to insee. -- WHN 2004-10-28
318   (random most-positive-fixnum
319           *instance-hash-code-random-state*))
320
321 (defun sb-impl::sxhash-instance (x)
322   (cond
323     ((std-instance-p x) (std-instance-hash x))
324     ((fsc-instance-p x) (fsc-instance-hash x))
325     (t (bug "SXHASH-INSTANCE called on some weird thing: ~S" x))))
326 \f
327 ;;;; structure-instance stuff
328 ;;;;
329 ;;;; FIXME: Now that the code is SBCL-only, this extra layer of
330 ;;;; abstraction around our native structure representation doesn't
331 ;;;; seem to add anything useful, and could probably go away.
332
333 ;;; The definition of STRUCTURE-TYPE-P was moved to early-low.lisp.
334
335 (defun structure-type-slot-description-list (type)
336   (let* ((dd (find-defstruct-description type))
337          (include (dd-include dd))
338          (all-slots (dd-slots dd)))
339     (multiple-value-bind (super slot-overrides)
340         (if (consp include)
341             (values (car include) (mapcar #'car (cdr include)))
342             (values include nil))
343       (let ((included-slots
344              (when super
345                (dd-slots (find-defstruct-description super)))))
346         (loop for slot = (pop all-slots)
347               for included-slot = (pop included-slots)
348               while slot
349               when (or (not included-slot)
350                        (member (dsd-name included-slot) slot-overrides :test #'eq))
351               collect slot)))))
352
353 (defun uninitialized-accessor-function (type slotd)
354   (lambda (&rest args)
355     (declare (ignore args))
356     (error "~:(~A~) function~@[ for ~S ~] not yet initialized."
357            type slotd)))
358
359 (defun structure-slotd-name (slotd)
360   (dsd-name slotd))
361
362 (defun structure-slotd-accessor-symbol (slotd)
363   (dsd-accessor-name slotd))
364
365 (defun structure-slotd-reader-function (slotd)
366   (let ((name (dsd-accessor-name slotd)))
367     (if (fboundp name)
368         (fdefinition name)
369         (uninitialized-accessor-function :reader slotd))))
370
371 (defun structure-slotd-writer-function (type slotd)
372   (if (dsd-read-only slotd)
373       (let ((dd (find-defstruct-description type)))
374         (coerce (slot-setter-lambda-form dd slotd) 'function))
375       (let ((name `(setf ,(dsd-accessor-name slotd))))
376         (if (fboundp name)
377             (fdefinition name)
378             (uninitialized-accessor-function :writer slotd)))))
379
380 (defun structure-slotd-type (slotd)
381   (dsd-type slotd))
382
383 (defun structure-slotd-init-form (slotd)
384   (dsd-default slotd))
385 \f
386 ;;; method function stuff.
387 ;;;
388 ;;; PCL historically included a so-called method-fast-function, which
389 ;;; is essentially a method function but with (a) a precomputed
390 ;;; continuation for CALL-NEXT-METHOD and (b) a permutation vector for
391 ;;; slot access.  [ FIXME: see if we can understand these two
392 ;;; optimizations before commit. ]  However, the presence of the
393 ;;; fast-function meant that we violated AMOP and the effect of the
394 ;;; :FUNCTION initarg, and furthermore got to potentially confusing
395 ;;; situations where the function and the fast-function got out of
396 ;;; sync, so that calling (method-function method) with the defined
397 ;;; protocol would do different things from (call-method method) in
398 ;;; method combination.
399 ;;;
400 ;;; So we define this internal method function structure, which we use
401 ;;; when we create a method function ourselves.  This means that we
402 ;;; can hang the various bits of information that we want off the
403 ;;; method function itself, and also that if a user overrides method
404 ;;; function creation there is no danger of having the system get
405 ;;; confused.
406 (!defstruct-with-alternate-metaclass %method-function
407   :slot-names (fast-function name)
408   :boa-constructor %make-method-function
409   :superclass-name function
410   :metaclass-name static-classoid
411   :metaclass-constructor make-static-classoid
412   :dd-type funcallable-structure)
413