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
40(eval-when (:compile-toplevel :load-toplevel :execute)
41(defvar *optimize-speed*
42  '(optimize (speed 3) (safety 0) (sb!ext:inhibit-warnings 3)))
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;;; Lambda which executes its body (or not) randomly. Used to drop
55;;; random cache entries.
56;;; This formerly punted with slightly greater than 50% probability,
57;;; and there was a periodicity to the nonrandomess.
58;;; If that was intentional, it should have been commented to that effect.
59(defmacro randomly-punting-lambda (lambda-list &body body)
60  (with-unique-names (drops drop-pos)
61    `(let ((,drops (random-fixnum)) ; means a POSITIVE fixnum
62           (,drop-pos sb!vm:n-positive-fixnum-bits))
63       (declare (fixnum ,drops)
64                (type (mod #.sb!vm:n-fixnum-bits) ,drop-pos))
65       (lambda ,lambda-list
66         (when (logbitp (the unsigned-byte (decf ,drop-pos)) ,drops)
67           (locally ,@body))
68         (when (zerop ,drop-pos)
69           (setf ,drops (random-fixnum)
70                 ,drop-pos sb!vm:n-positive-fixnum-bits))))))
71
72(import 'sb!kernel:funcallable-instance-p) ; why?
73
74(defun set-funcallable-instance-function (fin new-value)
75  (declare (type function new-value)
76           ;; KLUDGE: it might be nice to restrict
77           ;; SB-MOP:SET-FUNCALLABLE-INSTANCE-FUNCTION to operate only
78           ;; on generalized instances of
79           ;; SB-MOP:FUNCALLABLE-STANDARD-OBJECT; at present, even
80           ;; PCL's internal use of SET-FUNCALLABLE-INSTANCE-FUNCTION
81           ;; doesn't obey this restriction.
82           (type funcallable-instance fin))
83  (setf (funcallable-instance-fun fin) new-value))
84
85;;; FIXME: these macros should just go away.  It's not clear whether
86;;; the inline functions defined by
87;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS are as efficient as they could
88;;; be; ordinary defstruct accessors are defined as source transforms.
89(declaim (inline fsc-instance-p))
90(defun fsc-instance-p (fin)
91  (funcallable-instance-p fin))
92(defmacro fsc-instance-wrapper (fin)
93  `(%funcallable-instance-layout ,fin))
94(defmacro fsc-instance-slots (fin)
95  `(%funcallable-instance-info ,fin sb!vm:instance-data-start))
96
97(declaim (inline clos-slots-ref (setf clos-slots-ref)))
98(declaim (ftype (function (simple-vector index) t) clos-slots-ref))
99(defun clos-slots-ref (slots index)
100  (svref slots index))
101(declaim (ftype (function (t simple-vector index) t) (setf clos-slots-ref)))
102(defun (setf clos-slots-ref) (new-value slots index)
103  (setf (svref slots index) new-value))
104
105;;; Note on implementation under CMU CL >=17 and SBCL: STD-INSTANCE-P
106;;; is only used to discriminate between functions (including FINs)
107;;; and normal instances, so we can return true on structures also. A
108;;; few uses of (OR STD-INSTANCE-P FSC-INSTANCE-P) are changed to
109;;; PCL-INSTANCE-P.
110(declaim (inline std-instance-p))
111(defun std-instance-p (x)
112  (%instancep x))
113
114;;; When given a funcallable instance, SET-FUN-NAME *must* side-effect
115;;; that FIN to give it the name. When given any other kind of
116;;; function SET-FUN-NAME is allowed to return a new function which is
117;;; "the same" except that it has the name.
118;;;
119;;; In all cases, SET-FUN-NAME must return the new (or same)
120;;; function. (Unlike other functions to set stuff, it does not return
121;;; the new value.)
122;; This is an absolutely terrible name for a function which both assigns
123;; the name slot of a function, and _sometimes_ binds a name to a function.
124(defun set-fun-name (fun new-name)
125  #!+sb-doc
126  "Set the name of a compiled function object. Return the function."
127  (when (valid-function-name-p fun)
128    (setq fun (fdefinition fun)))
129  (typecase fun
130    (%method-function (setf (%method-function-name fun) new-name))
131    ;; a closure potentially becomes a different closure
132    (closure (setq fun (sb!impl::set-closure-name fun new-name)))
133    (t (setf (%fun-name fun) new-name)))
134  ;; Fixup name-to-function mappings in cases where the function
135  ;; hasn't been defined by DEFUN.  (FIXME: is this right?  This logic
136  ;; comes from CMUCL).  -- CSR, 2004-12-31
137  ;;
138  ;; Now, given this logic is somewhat suspect to begin with, and is the final
139  ;; remaining contributor to the immortalization of EQL-specialized methods,
140  ;; I'm going to say that we don't create an fdefn for anything
141  ;; whose specializers are not symbols.
142  ;; Otherwise, adding+removing N methods named
143  ;;  (SLOW-METHOD BLAH ((EQL <HAIRY-LIST-OBJECT>)))
144  ;; makes them all permanent because FDEFNs are compared by name EQUALity,
145  ;; so each gets its own FDEFN. This is bad, and pretty much useless anyway.
146  (when (and (consp new-name)
147             (or (eq (car new-name) 'slot-accessor)
148                 (and (member (car new-name) '(slow-method fast-method))
149                      ;; name is: ({SLOW|FAST}-METHOD root <qual>* spec+)
150                      (every #'symbolp (car (last new-name))))))
151    (setf (fdefinition new-name) fun))
152  fun)
153
154;;; FIXME: probably no longer needed after init
155(defmacro precompile-random-code-segments (&optional system)
156  `(progn
157     (eval-when (:compile-toplevel)
158       (update-dispatch-dfuns))
159     (precompile-function-generators ,system)
160     (precompile-dfun-constructors ,system)
161     (precompile-ctors)))
162
163;;; Return true of any object which is either a funcallable-instance,
164;;; or an ordinary instance that is not a structure-object.
165;;; This used to be implemented as (LAYOUT-FOR-STD-CLASS-P (LAYOUT-OF x))
166;;; but LAYOUT-OF is more general than need be here. So this bails out
167;;; after the first two clauses of the equivalent COND in LAYOUT-OF
168;;; because nothing else could possibly return T.
169(declaim (inline %pcl-instance-p))
170(defun %pcl-instance-p (x)
171  (layout-for-std-class-p
172   (cond ((%instancep x) (%instance-layout x))
173         ((funcallable-instance-p x) (%funcallable-instance-layout x))
174         (t (return-from %pcl-instance-p nil)))))
175
176;;; This definition is for interpreted code.
177(defun pcl-instance-p (x) (declare (explicit-check)) (%pcl-instance-p x))
178
179;;; Both of these operations "work" on structures, which allows the above
180;;; weakening of STD-INSTANCE-P.
181;;; FIXME: what does the preceding comment mean? You can't use instance-slots
182;;; on a structure. (Consider especially a structure of 0 slots.)
183(defmacro std-instance-slots (x) `(%instance-ref ,x sb!vm:instance-data-start))
184(defmacro std-instance-wrapper (x) `(%instance-layout ,x))
185
186;;; FIXME: These functions are called every place we do a
187;;; CALL-NEXT-METHOD, and probably other places too. It's likely worth
188;;; selectively optimizing them with DEFTRANSFORMs and stuff, rather
189;;; than just indiscriminately expanding them inline everywhere.
190(declaim (inline get-slots get-slots-or-nil))
191(declaim (ftype (function (t) simple-vector) get-slots))
192(declaim (ftype (function (t) (or simple-vector null)) get-slots-or-nil))
193(defun get-slots (instance)
194  (if (std-instance-p instance)
195      (std-instance-slots instance)
196      (fsc-instance-slots instance)))
197(defun get-slots-or-nil (instance)
198  ;; Suppress a code-deletion note.  FIXME: doing the FIXME above,
199  ;; integrating PCL more with the compiler, would remove the need for
200  ;; this icky stuff.
201  (declare (optimize (inhibit-warnings 3)))
202  (when (pcl-instance-p instance)
203    (get-slots instance)))
204
205;; This macro is used only by %CHANGE-CLASS. Can we just do this there?
206;; [The code in 'fsc.lisp' which looks like it needs it is commented out]
207(defmacro get-wrapper (inst)
208  (once-only ((wrapper `(layout-of ,inst)))
209    `(progn
210       (aver (layout-for-std-class-p ,wrapper))
211       ,wrapper)))
212
213;;;; structure-instance stuff
214;;;;
215;;;; FIXME: Now that the code is SBCL-only, this extra layer of
216;;;; abstraction around our native structure representation doesn't
217;;;; seem to add anything useful, and could probably go away.
218
219;;; The definition of STRUCTURE-TYPE-P was moved to early-low.lisp.
220
221(defun structure-type-slot-description-list (type)
222  (let* ((dd (find-defstruct-description type))
223         (include (dd-include dd))
224         (all-slots (dd-slots dd)))
225    (multiple-value-bind (super slot-overrides)
226        (if (consp include)
227            (values (car include) (mapcar #'car (cdr include)))
228            (values include nil))
229      (let ((included-slots
230             (when super
231               (dd-slots (find-defstruct-description super)))))
232        (loop for slot = (pop all-slots)
233              for included-slot = (pop included-slots)
234              while slot
235              when (or (not included-slot)
236                       (member (dsd-name included-slot) slot-overrides :test #'eq))
237              collect slot)))))
238
239(defun uninitialized-accessor-function (type slotd)
240  (lambda (&rest args)
241    (declare (ignore args))
242    (error "~:(~A~) function~@[ for ~S ~] not yet initialized."
243           type slotd)))
244
245(defun structure-slotd-name (slotd)
246  (dsd-name slotd))
247
248(defun structure-slotd-accessor-symbol (slotd)
249  (dsd-accessor-name slotd))
250
251(defun structure-slotd-reader-function (slotd)
252  (let ((name (dsd-accessor-name slotd)))
253    (if (fboundp name)
254        (fdefinition name)
255        (uninitialized-accessor-function :reader slotd))))
256
257;;; Return a function to write the slot identified by SLOTD.
258;;; This is easy for read/write slots - we just return the accessor
259;;; that was already set up - but it requires work for read-only slots.
260;;; Basically we get the slotter-setter-lambda-form and compile it.
261;;; Using (COERCE lambda-form 'FUNCTION) as used to be done might produce
262;;; an interpreted function. I'm not sure whether that's right or wrong,
263;;; because if the DEFSTRUCT itself were evaluated, then the ordinary
264;;; accessors would indeed be interpreted. However if the DEFSTRUCT were
265;;; compiled, and the fasl loaded in a Lisp with *EVALUATOR-MODE* = :INTERPRET,
266;;; arguably this is against the expectation that all things got compiled.
267;;; But can people really expect that manipulating read-only slots
268;;; via (SETF SLOT-VALUE) should be fast?
269;;;
270;;; Damned-if-you-do / damned-if-you don't - the best thing would be to
271;;; compile all accessors at "really" compile-time but not store the writer
272;;; for a reaadonly slot under the #<fdefn> for #'(SETF slot-name).
273;;;
274(defun structure-slotd-writer-function (type slotd)
275  ;; TYPE is not used, because the DD is taken from runtime data.
276  (declare (ignore type))
277  (if (dsd-read-only slotd)
278      ;; We'd like to compile the writer just-in-time and store it
279      ;; back into the STRUCTURE-DIRECT-SLOT-DEFINITION and also
280      ;; the LAYOUT for the class, but we don't have a handle on
281      ;; any of the containing objects. So this has to be a closure.
282      (let ((setter 0))
283        (lambda (newval instance)
284          (if (eql setter 0)
285              (let* ((dd (layout-info (%instance-layout instance)))
286                     (f (compile nil (slot-setter-lambda-form dd slotd))))
287                (if (functionp f)
288                    (funcall (setq setter f) newval instance)
289                    (uninitialized-accessor-function :writer slotd)))
290              (funcall (truly-the function setter) newval instance))))
291      (let ((name `(setf ,(dsd-accessor-name slotd))))
292        (if (fboundp name)
293            (fdefinition name)
294            (uninitialized-accessor-function :writer slotd)))))
295
296(defun structure-slotd-type (slotd)
297  (dsd-type slotd))
298
299(defun structure-slotd-init-form (slotd)
300  (dsd-default slotd))
301