0.9.0.25:
[sbcl.git] / contrib / sb-introspect / sb-introspect.lisp
1 ;;; introspection library
2
3 ;;; This is here as a discussion point, not yet a supported interface.  If
4 ;;; you would like to use the functions here, or you would like other
5 ;;; functions to be here, join the debate on navel@metacircles.com.
6 ;;; List info at http://lists.metacircles.com/cgi-bin/mailman/listinfo/navel
7
8 ;;; For the avoidance of doubt, the exported interface is the proposed
9 ;;; supported interface.  Anything else is internal, though you're
10 ;;; welcome to argue a case for exporting it.
11
12 ;;; If you steal the code from this file to cut and paste into your
13 ;;; own project, there will be much wailing and gnashing of teeth.
14 ;;; Your teeth.  If need be, we'll kick them for you.  This is a
15 ;;; contrib, we're allowed to look in internals.  You're an
16 ;;; application programmer, and are not.
17
18 ;;; TODO
19 ;;; 1) structs don't have within-file location info.  problem for the
20 ;;;   structure itself, accessors and the predicate
21 ;;; 2) what should find-definition-source on a symbol return?  there may be
22 ;;;   several definitions (class, function, etc)
23 ;;; 3) error handling.  Signal random errors, or handle and resignal 'our'
24 ;;;   error, or return NIL?
25 ;;; 4) FIXMEs
26 ;;; 5) would be nice to have some interface to the compiler that lets us
27 ;;;   fake the filename and position, for use with C-M-x
28
29 (defpackage :sb-introspect
30   (:use "CL")
31   (:export "FUNCTION-ARGLIST" "VALID-FUNCTION-NAME-P"
32            "FIND-DEFINITION-SOURCE"
33            "DEFINITION-SOURCE" "DEFINITION-SOURCE-PATHNAME"
34            "DEFINITION-NOT-FOUND" "DEFINITION-NAME"
35            "DEFINITION-SOURCE-FORM-PATH"
36            "DEFINITION-SOURCE-CHARACTER-OFFSET"
37            "DEFINITION-SOURCE-FILE-WRITE-DATE"
38            "FIND-FUNCTION-CALLEES"
39            "FIND-FUNCTION-CALLERS"
40            ))
41 (in-package :sb-introspect)
42
43 ;;;; Internal interface for SBCL debug info
44
45 ;;; Here are some tutorial-style type definitions to help understand
46 ;;; the internal SBCL debugging data structures we're using. The
47 ;;; commentary is based on CMUCL's debug internals manual.
48 ;;;
49 (deftype debug-info ()
50   "Structure containing all the debug information related to a function.
51 Function objects reference debug-infos which in turn reference
52 debug-sources and so on."
53   'sb-c::compiled-debug-info)
54
55 (deftype debug-source ()
56   "Debug sources describe where to find source code.
57 For example, the debug source for a function compiled from a file will
58 include the pathname of the file and the position of the definition."
59   'sb-c::debug-source)
60
61 (deftype debug-function ()
62   "Debug function represent static compile-time information about a function."
63   'sb-c::compiled-debug-fun)
64
65 (declaim (ftype (function (function) debug-info) function-debug-info))
66 (defun function-debug-info (function)
67   (let* ((function-object (sb-kernel::%closure-fun function))
68          (function-header (sb-kernel:fun-code-header function-object)))
69     (sb-kernel:%code-debug-info function-header)))
70
71 (declaim (ftype (function (function) debug-source) function-debug-source))
72 (defun function-debug-source (function)
73   (debug-info-source (function-debug-info function)))
74
75 (declaim (ftype (function (debug-info) debug-source) debug-info-source))
76 (defun debug-info-source (debug-info)
77   (destructuring-bind (debug-source &rest other-debug-sources)
78       (sb-c::compiled-debug-info-source debug-info)
79     ;; COMPILED-DEBUG-INFO-SOURCES can return a list but we expect
80     ;; this to always contain exactly one element in SBCL. The list
81     ;; interface is inherited from CMUCL. -luke (12/Mar/2005)
82     (assert (null other-debug-sources))
83     debug-source))
84
85 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
86 (defun debug-info-debug-function (debug-info)
87   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
88
89 (defun valid-function-name-p (name)
90   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
91   (and (sb-int:valid-function-name-p name) t))
92
93 ;;;; Finding definitions
94
95 (defstruct definition-source
96   ;; Pathname of the source file that the definition was compiled from.
97   ;; This is null if the definition was not compiled from a file.
98   (pathname nil :type (or null pathname))
99   ;; Source-path of the definition within the file.
100   ;; This may be incomplete depending on the debug level at which the
101   ;; source was compiled.
102   (form-path '() :type list)
103   ;; Character offset of the top-level-form containing the definition.
104   ;; This corresponds to the first element of form-path.
105   (character-offset nil :type (or null integer))
106   ;; File-write-date of the source file when compiled.
107   ;; Null if not compiled from a file.
108   (file-write-date nil :type (or null integer)))
109
110 (defun find-definition-source (object)
111   (etypecase object
112     (method
113      (find-definition-source (or (sb-pcl::method-fast-function object)
114                                  (sb-pcl:method-function object))))
115     (function
116      (cond ((struct-accessor-p object)
117             (find-definition-source (struct-accessor-structure-class object)))
118            ((struct-predicate-p object)
119             (find-definition-source (struct-predicate-structure-class object)))
120            (t (find-function-definition-source object))))
121     (structure-class
122      (let ((constructor
123             (sb-kernel::structure-classoid-constructor
124              (sb-kernel:classoid-cell-classoid
125               (sb-int:info :type :classoid (class-name object))))))
126        (find-definition-source constructor)))
127     (t
128      (if (valid-function-name-p object)
129          (find-definition-source (or (macro-function object)
130                                      (fdefinition object)))))))
131
132 (defun find-function-definition-source (function)
133   (let* ((debug-info (function-debug-info function))
134          (debug-source (debug-info-source debug-info))
135          (debug-fun (debug-info-debug-function debug-info))
136          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
137     (make-definition-source
138      :pathname
139      (if (eql (sb-c::debug-source-from debug-source) :file)
140          (parse-namestring (sb-c::debug-source-name debug-source)))
141      :character-offset
142      (if tlf
143          (elt (sb-c::debug-source-start-positions debug-source) tlf))
144      ;; Unfortunately there is no proper source path available in the
145      ;; debug-source. FIXME: We could use sb-di:code-locations to get
146      ;; a full source path. -luke (12/Mar/2005)
147      :form-path (if tlf (list tlf))
148      :file-write-date (sb-c::debug-source-created debug-source))))
149
150 ;;; This is kludgey.  We expect these functions (the underlying functions,
151 ;;; not the closures) to be in static space and so not move ever.
152 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
153 ;;; accessors, e.g. when the :type option is used
154 (defvar *struct-slotplace-reader*
155   (sb-vm::%simple-fun-self #'definition-source-pathname))
156 (defvar *struct-slotplace-writer*
157   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
158 (defvar *struct-predicate*
159   (sb-vm::%simple-fun-self #'definition-source-p))
160
161 (defun struct-accessor-p (function)
162   (let ((self (sb-vm::%simple-fun-self function)))
163     ;; FIXME there are other kinds of struct accessor.  Fill out this list
164     (member self (list *struct-slotplace-reader*
165                        *struct-slotplace-writer*))))
166
167 (defun struct-predicate-p (function)
168   (let ((self (sb-vm::%simple-fun-self function)))
169     ;; FIXME there may be other structure predicate functions
170     (member self (list *struct-predicate*))))
171
172 ;;; FIXME: maybe this should be renamed as FUNCTION-LAMBDA-LIST?
173 (defun function-arglist (function)
174   "Describe the lambda list for the function designator FUNCTION.
175 Works for special-operators, macros, simple functions and generic
176 functions.  Signals error if not found"
177   (cond ((valid-function-name-p function) 
178          (function-arglist
179           (or (macro-function function) (fdefinition function))))
180         ((typep function 'generic-function)
181          (sb-pcl::generic-function-pretty-arglist function))
182         (t (sb-impl::%simple-fun-arglist
183             (sb-impl::%closure-fun function)))))
184
185 (defun struct-accessor-structure-class (function)
186   (let ((self (sb-vm::%simple-fun-self function)))
187     (cond
188       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
189        (find-class
190         (sb-kernel::classoid-name
191          (sb-kernel::layout-classoid
192           (sb-kernel:%closure-index-ref function 1)))))
193       )))
194
195 (defun struct-predicate-structure-class (function)
196   (let ((self (sb-vm::%simple-fun-self function)))
197     (cond
198       ((member self (list *struct-predicate*))
199        (find-class
200         (sb-kernel::classoid-name
201          (sb-kernel::layout-classoid
202           (sb-kernel:%closure-index-ref function 0)))))
203       )))
204
205 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
206
207 ;;; This interface is trmendously experimental.  
208
209 ;;; For the moment I'm taking the view that FDEFN is an internal
210 ;;; object (one out of one CMUCL developer surveyed didn't know what
211 ;;; they were for), so these routines deal in FUNCTIONs
212
213 ;;; Find callers and callees by looking at the constant pool of
214 ;;; compiled code objects.  We assume every fdefn object in the
215 ;;; constant pool corresponds to a call to that function.  A better
216 ;;; strategy would be to use the disassembler to find actual
217 ;;; call-sites.
218
219 (defun find-function-callees (function)
220   "Return functions called by FUNCTION."
221   (let ((callees '()))
222     (map-code-constants 
223      (sb-kernel:fun-code-header function)
224      (lambda (obj)
225        (when (sb-kernel:fdefn-p obj)
226          (push (sb-kernel:fdefn-fun obj) 
227                callees))))
228     callees))
229
230
231 (defun find-function-callers (function &optional (spaces '(:read-only :static 
232                                                            :dynamic)))
233   "Return functions which call FUNCTION, by searching SPACES for code objects"
234   (let ((referrers '()))
235     (map-caller-code-components 
236      function
237      spaces
238      (lambda (code)
239        (let ((entry (sb-kernel:%code-entry-points  code)))
240          (cond ((not entry)
241                 (push (princ-to-string code) referrers))
242                (t 
243                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
244                       while e
245                       do (pushnew e referrers)))))))
246     referrers))
247
248 (declaim (inline map-code-constants))
249 (defun map-code-constants (code fn)
250   "Call FN for each constant in CODE's constant pool."
251   (check-type code sb-kernel:code-component)
252   (loop for i from sb-vm:code-constants-offset below 
253         (sb-kernel:get-header-data code)
254         do (funcall fn (sb-kernel:code-header-ref code i))))
255
256 (declaim (inline map-allocated-code-components))
257 (defun map-allocated-code-components (spaces fn)
258   "Call FN for each allocated code component in one of SPACES.  FN
259 receives the object and its size as arguments.  SPACES should be a
260 list of the symbols :dynamic, :static, or :read-only."
261   (dolist (space spaces)
262     (sb-vm::map-allocated-objects
263      (lambda (obj header size)
264        (when (= sb-vm:code-header-widetag header)
265          (funcall fn obj size)))
266      space)))
267
268 (declaim (inline map-caller-code-components))
269 (defun map-caller-code-components (function spaces fn)
270   "Call FN for each code component with a fdefn for FUNCTION in its
271 constant pool."
272   (let ((function (coerce function 'function)))
273     (map-allocated-code-components
274      spaces 
275      (lambda (obj size)
276        (declare (ignore size))
277        (map-code-constants 
278         obj 
279         (lambda (constant)
280           (when (and (sb-kernel:fdefn-p constant)
281                      (eq (sb-kernel:fdefn-fun constant)
282                          function))
283             (funcall fn obj))))))))
284
285 (provide 'sb-introspect)