0.6.11.10:
[sbcl.git] / src / code / fdefinition.lisp
1 ;;;; This file contains functions that hack on the global function
2 ;;;; namespace (primarily concerned with SETF functions here). Also,
3 ;;;; function encapsulation and routines that set and return
4 ;;;; definitions disregarding whether they might be encapsulated.
5
6 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; more information.
8 ;;;;
9 ;;;; This software is derived from the CMU CL system, which was
10 ;;;; written at Carnegie Mellon University and released into the
11 ;;;; public domain. The software is in the public domain and is
12 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
13 ;;;; files for more information.
14
15 (in-package "SB!IMPL")
16
17 (sb!int::/show0 "fdefinition.lisp 22")
18 \f
19 ;;;; fdefinition (fdefn) objects
20
21 (defun make-fdefn (name)
22   (make-fdefn name))
23
24 (defun fdefn-name (fdefn)
25   (declare (type fdefn fdefn))
26   (fdefn-name fdefn))
27
28 (defun fdefn-function (fdefn)
29   (declare (type fdefn fdefn)
30            (values (or function null)))
31   (fdefn-function fdefn))
32
33 (defun (setf fdefn-function) (fun fdefn)
34   (declare (type function fun)
35            (type fdefn fdefn)
36            (values function))
37   (setf (fdefn-function fdefn) fun))
38
39 (defun fdefn-makunbound (fdefn)
40   (declare (type fdefn fdefn))
41   (fdefn-makunbound fdefn))
42
43 ;;; This function is called by !COLD-INIT after the globaldb has been
44 ;;; initialized, but before anything else. We need to install these
45 ;;; fdefn objects into the globaldb before any top level forms run, or
46 ;;; we will end up with two different fdefn objects being used for the
47 ;;; same function name. *!INITIAL-FDEFN-OBJECTS* is set up by GENESIS.
48 (defvar *!initial-fdefn-objects*)
49 (defun !fdefn-cold-init ()
50   (dolist (fdefn *!initial-fdefn-objects*)
51     (setf (info :function :definition (fdefn-name fdefn)) fdefn)))
52
53 (defun fdefinition-object (name create)
54   #!+sb-doc
55   "Return the fdefn object for NAME. If it doesn't already exist and CREATE
56    is non-NIL, create a new (unbound) one."
57   (declare (values (or fdefn null)))
58   (unless (or (symbolp name)
59               (and (consp name)
60                    (eq (car name) 'setf)
61                    (let ((cdr (cdr name)))
62                      (and (consp cdr)
63                           (symbolp (car cdr))
64                           (null (cdr cdr))))))
65     (error 'simple-type-error
66            :datum name
67            :expected-type '(or symbol list)
68            :format-control "invalid function name: ~S"
69            :format-arguments (list name)))
70   (let ((fdefn (info :function :definition name)))
71     (if (and (null fdefn) create)
72         (setf (info :function :definition name) (make-fdefn name))
73         fdefn)))
74
75 ;;; FIXME: If the fundamental operation performed when
76 ;;; funcalling a symbol is %COERCE-NAME-TO-FUNCTION, which expands into
77 ;;; FDEFINITION-OBJECT, which does (INFO :FUNCTION :DEFINITION NAME),
78 ;;; that's a horrendously heavyweight way to implement SYMBOL-FUNCTION.
79 ;;; What compelling reason is there for all this hairiness? The only
80 ;;; thing I can think of is that it does give a place to store
81 ;;; SETF functions, but I don't think that's a good enough reason.
82 ;;; It might even be that the FDEFINITION arrangement saves a little
83 ;;; space, if the proportion of function-less symbols is high enough,
84 ;;; but I don't think that's a good enough reason, either.
85 ;;; I'd really like to wipe out FDEFN stuff root and branch, and
86 ;;; just store SETF functions in the symbol property list.
87 ;;;
88 ;;; One problem with just doing the simple thing: What happens when
89 ;;; people call symbols which have no function definitions?
90 ;;;   1. Just hit "undefined function" error -- with no clue as to
91 ;;;      what undefined function it was. (This might actually not be
92 ;;;      too horrible, since the compiler warns you about undefined
93 ;;;      functions and the debugger aims, with incomplete success,
94 ;;;      to show you what form caused an error.)
95 ;;;   2. various solutions involving closures in the function slot,
96 ;;;      all of which have the drawback of extra memory use and extra
97 ;;;      difficulty in detecting when functions are undefined
98 ;;;   2a. Have every single symbol have an undefined function closure
99 ;;;       which points back to it to tell you which undefined symbol it
100 ;;;       was. (4 extra words per undefined symbol)
101 ;;;   2b. Play tricks with FDEFINITION, where the default SYMBOL-FUNCTION
102 ;;;       for any function is an anonymous "undefined function" error
103 ;;;       which doesn't tell you what the problem was, but if FDEFINITION
104 ;;;       is ever called on an undefined symbol, it helpfully changes the
105 ;;;       function definition to point to a closure which knows which
106 ;;;       symbol caused the problem.
107 ;;;   4. Just don't sweat it except when DEBUG>SPEED, where the calling
108 ;;;      convention gets tweaked to test for the undefined-function
109 ;;;      function at call time and bail out with helpful information
110 ;;;      if it's there.
111 ;;;   5. Require that the function calling convention be stereotyped
112 ;;;      along the lines of
113 ;;;             mov %ebx, local_immediate_3         ; Point to symbol.
114 ;;;             mov %eax, symbol_function_offset(%eax) ; Point to function.
115 ;;;             call *function_code_pointer(%eax)      ; Go.
116 ;;;      That way, it's guaranteed that on entry to a function, %EBX points
117 ;;;      back to the symbol which was used to indirect into the function,
118 ;;;      so the undefined function handler can base its complaint on that.
119 ;;;
120 ;;; Another problem with doing the simple thing: people will want to
121 ;;; indirect through something in order to get to SETF functions, in
122 ;;; order to be able to redefine them. What will they indirect
123 ;;; through? This could be done with a hack, making an anonymous
124 ;;; symbol and linking it to the main symbol's SB!KERNEL:SETF-FUNCTION
125 ;;; property. The anonymous symbol could even point back to the symbol
126 ;;; it's the SETF function for, so that if the SETF function was
127 ;;; undefined at the time a call was made, the debugger could say
128 ;;; which function caused the problem. It'd probably be cleaner,
129 ;;; though, to use a new type of primitive object (SYMBOLOID?)
130 ;;; instead. It could probably be like symbol except that its name
131 ;;; could be any object and its value points back to the symbol which
132 ;;; owns it. Then the setf functions for FOO could be on the list (GET
133 ;;; FOO 'SB!KERNEL:SYMBOLOIDS)
134 ;;;
135 ;;; FIXME: Oh, my. Now that I've started thinking about it, I
136 ;;; appreciate more fully how weird and twisted FDEFNs might be. Look
137 ;;; at the calling sequence for full calls. It goes and reads the
138 ;;; address of a function object from its own table of immediate
139 ;;; values, then jumps into that. Consider how weird that is. Not only
140 ;;; is it not doing indirection through a symbol (which I'd already
141 ;;; realized) but it's not doing indirection through
142
143 ;;; The compiler emits calls to this when someone tries to funcall a symbol.
144 (defun %coerce-name-to-function (name)
145   #!+sb-doc
146   "Returns the definition for name, including any encapsulations. Settable
147    with SETF."
148   (let ((fdefn (fdefinition-object name nil)))
149     (or (and fdefn (fdefn-function fdefn))
150         (error 'undefined-function :name name))))
151
152 (defun %coerce-callable-to-function (callable)
153   (if (functionp callable)
154       callable
155       (%coerce-name-to-function callable)))
156
157 ;;; This is just another name for %COERCE-NAME-TO-FUNCTION.
158 #!-sb-fluid (declaim (inline raw-definition))
159 (defun raw-definition (name)
160   ;; We know that we are calling %COERCE-NAME-TO-FUNCTION, so don't remind us.
161   (declare (optimize (inhibit-warnings 3)))
162   (%coerce-name-to-function name))
163 (defun (setf raw-definition) (function name)
164   (let ((fdefn (fdefinition-object name t)))
165     (setf (fdefn-function fdefn) function)))
166
167 ;;; FIXME: There seems to be no good reason to have both
168 ;;; %COERCE-NAME-TO-FUNCTION and RAW-DEFINITION names for the same
169 ;;; thing. And despite what the doc string of %COERCE-NAME-TO-FUNCTION
170 ;;; says, it's doesn't look settable. Perhaps we could collapse
171 ;;; %COERCE-TO-FUNCTION, RAW-DEFINITION, and (SETF RAW-DEFINITION)
172 ;;; into RAW-FDEFINITION and (SETF RAW-FDEFINITION), or
173 ;;; OUTER-FDEFINITION and (SETF OUTER-FDEFINITION).
174 \f
175 ;;;; definition encapsulation
176
177 (defstruct (encapsulation-info (:constructor make-encapsulation-info
178                                              (type definition))
179                                (:copier nil))
180   ;; This is definition's encapsulation type. The encapsulated
181   ;; definition is in the previous encapsulation-info element or
182   ;; installed as the global definition of some function name.
183   type
184   ;; the previous, encapsulated definition. This used to be installed
185   ;; as a global definition for some function name, but it was
186   ;; replaced by an encapsulation of type TYPE.
187   (definition nil :type function))
188
189 ;;; We must bind and close over info. Consider the case where we
190 ;;; encapsulate (the second) an encapsulated (the first) definition,
191 ;;; and later someone unencapsulates the encapsulated (first)
192 ;;; definition. We don't want our encapsulation (second) to bind
193 ;;; basic-definition to the encapsulated (first) definition when it no
194 ;;; longer exists. When unencapsulating, we make sure to clobber the
195 ;;; appropriate info structure to allow basic-definition to be bound
196 ;;; to the next definition instead of an encapsulation that no longer
197 ;;; exists.
198 (defun encapsulate (name type body)
199   #!+sb-doc
200   "Replaces the definition of NAME with a function that binds name's arguments
201    a variable named argument-list, binds name's definition to a variable named
202    basic-definition, and evaluates BODY in that context. TYPE is
203    whatever you would like to associate with this encapsulation for
204    identification in case you need multiple encapsuations of the same name."
205   (let ((fdefn (fdefinition-object name nil)))
206     (unless (and fdefn (fdefn-function fdefn))
207       (error 'undefined-function :name name))
208     (let ((info (make-encapsulation-info type (fdefn-function fdefn))))
209       (setf (fdefn-function fdefn)
210             #'(lambda (&rest argument-list)
211                 (declare (special argument-list))
212                 (let ((basic-definition (encapsulation-info-definition info)))
213                   (declare (special basic-definition))
214                   (eval body)))))))
215
216 ;;; Finds the encapsulation info that has been closed over.
217 (defun encapsulation-info (fun)
218   (and (functionp fun)
219        (= (get-type fun) sb!vm:closure-header-type)
220        (find-if-in-closure #'encapsulation-info-p fun)))
221
222 ;;; When removing an encapsulation, we must remember that
223 ;;; encapsulating definitions close over a reference to the
224 ;;; encapsulation-info that describes the encapsulating definition.
225 ;;; When you find an info with the target type, the previous info in
226 ;;; the chain has the ensulating definition of that type. We take the
227 ;;; encapsulated definition from the info with the target type, and we
228 ;;; store it in the previous info structure whose encapsulating
229 ;;; definition it describes looks to this previous info structure for
230 ;;; a definition to bind (see ENCAPSULATE). When removing the first
231 ;;; info structure, we do something conceptually equal, but
232 ;;; mechanically it is different.
233 (defun unencapsulate (name type)
234   #!+sb-doc
235   "Removes NAME's most recent encapsulation of the specified TYPE."
236   (let* ((fdefn (fdefinition-object name nil))
237          (encap-info (encapsulation-info (fdefn-function fdefn))))
238     (declare (type (or encapsulation-info null) encap-info))
239     (cond ((not encap-info)
240            ;; It disappeared on us, so don't worry about it.
241            )
242           ((eq (encapsulation-info-type encap-info) type)
243            ;; It's the first one, so change the fdefn object.
244            (setf (fdefn-function fdefn)
245                  (encapsulation-info-definition encap-info)))
246           (t
247            ;; It must be an interior one, so find it.
248            (loop
249              (let ((next-info (encapsulation-info
250                                (encapsulation-info-definition encap-info))))
251                (unless next-info
252                  ;; Not there, so don't worry about it.
253                  (return))
254                (when (eq (encapsulation-info-type next-info) type)
255                  ;; This is it, so unlink us.
256                  (setf (encapsulation-info-definition encap-info)
257                        (encapsulation-info-definition next-info))
258                  (return))
259                (setf encap-info next-info))))))
260   t)
261
262 (defun encapsulated-p (name type)
263   #!+sb-doc
264   "Returns t if name has an encapsulation of the given type, otherwise nil."
265   (let ((fdefn (fdefinition-object name nil)))
266     (do ((encap-info (encapsulation-info (fdefn-function fdefn))
267                      (encapsulation-info
268                       (encapsulation-info-definition encap-info))))
269         ((null encap-info) nil)
270       (declare (type (or encapsulation-info null) encap-info))
271       (when (eq (encapsulation-info-type encap-info) type)
272         (return t)))))
273 \f
274 ;;;; FDEFINITION
275
276 ;;; KLUDGE: Er, it looks as though this means that
277 ;;;    (FUNCALL (FDEFINITION 'FOO))
278 ;;; doesn't do the same thing as
279 ;;;    (FUNCALL 'FOO).
280 ;;; That doesn't look like ANSI behavior to me. Look e.g. at the
281 ;;; ANSI definition of TRACE: "Whenever a traced function is invoked,
282 ;;; information about the call, ..". Try this:
283 ;;;   (DEFUN FOO () (PRINT "foo"))
284 ;;;   (TRACE FOO)
285 ;;;   (FUNCALL 'FOO)
286 ;;;   (FUNCALL (FDEFINITION 'FOO))
287 ;;; What to do? ANSI says TRACE "Might change the definitions of the functions
288 ;;; named by function-names." Might it be OK to just get punt all this
289 ;;; encapsulation stuff and go back to a simple but correct implementation of
290 ;;; TRACE? We'd lose the ability to redefine a TRACEd function and keep the
291 ;;; trace in place, but that seems tolerable to me. (Is the wrapper stuff
292 ;;; needed for anything else besides TRACE?)
293 ;;;
294 ;;; The only problem I can see with not having a wrapper: If tracing
295 ;;; EQ, EQL, EQUAL, or EQUALP causes its function address to change,
296 ;;; it will mess up the MAKE-HASH-TABLE logic which uses EQ tests
297 ;;; on those function values. -- WHN 19990906
298 (defun fdefinition (name)
299   #!+sb-doc
300   "Return name's global function definition taking care to respect any
301    encapsulations and to return the innermost encapsulated definition.
302    This is SETF'able."
303   (let ((fun (raw-definition name)))
304     (loop
305       (let ((encap-info (encapsulation-info fun)))
306         (if encap-info
307             (setf fun (encapsulation-info-definition encap-info))
308             (return fun))))))
309
310 (defvar *setf-fdefinition-hook* nil
311   #!+sb-doc
312   "This holds functions that (SETF FDEFINITION) invokes before storing the
313    new value. These functions take the function name and the new value.")
314
315 (defun %set-fdefinition (name new-value)
316   #!+sb-doc
317   "Set NAME's global function definition."
318   (declare (type function new-value) (optimize (safety 1)))
319   (let ((fdefn (fdefinition-object name t)))
320     ;; *SETF-FDEFINITION-HOOK* won't be bound when initially running top-level
321     ;; forms in the kernel core startup.
322     (when (boundp '*setf-fdefinition-hook*)
323       (dolist (f *setf-fdefinition-hook*)
324         (funcall f name new-value)))
325
326     (let ((encap-info (encapsulation-info (fdefn-function fdefn))))
327       (cond (encap-info
328              (loop
329                (let ((more-info
330                       (encapsulation-info
331                        (encapsulation-info-definition encap-info))))
332                  (if more-info
333                      (setf encap-info more-info)
334                      (return
335                       (setf (encapsulation-info-definition encap-info)
336                             new-value))))))
337             (t
338              (setf (fdefn-function fdefn) new-value))))))
339 \f
340 ;;;; FBOUNDP and FMAKUNBOUND
341
342 (defun fboundp (name)
343   #!+sb-doc
344   "Return true if name has a global function definition."
345   (let ((fdefn (fdefinition-object name nil)))
346     (and fdefn (fdefn-function fdefn) t)))
347
348 (defun fmakunbound (name)
349   #!+sb-doc
350   "Make Name have no global function definition."
351   (let ((fdefn (fdefinition-object name nil)))
352     (when fdefn
353       (fdefn-makunbound fdefn)))
354   name)