0.9.7.31:
[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 ;;; 3) error handling.  Signal random errors, or handle and resignal 'our'
22 ;;;   error, or return NIL?
23 ;;; 4) FIXMEs
24
25 (defpackage :sb-introspect
26   (:use "CL")
27   (:export "FUNCTION-ARGLIST"
28            "VALID-FUNCTION-NAME-P"
29            "FIND-DEFINITION-SOURCE"
30            "FIND-DEFINITION-SOURCES-BY-NAME"
31            "DEFINITION-SOURCE"
32            "DEFINITION-SOURCE-PATHNAME"
33            "DEFINITION-SOURCE-FORM-PATH"
34            "DEFINITION-SOURCE-CHARACTER-OFFSET"
35            "DEFINITION-SOURCE-FILE-WRITE-DATE"
36            "DEFINITION-SOURCE-PLIST"
37            "DEFINITION-NOT-FOUND" "DEFINITION-NAME"
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   (sb-c::debug-info-source debug-info))
78
79 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
80 (defun debug-info-debug-function (debug-info)
81   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
82
83 (defun valid-function-name-p (name)
84   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
85   (and (sb-int:valid-function-name-p name) t))
86
87 ;;;; Finding definitions
88
89 (defstruct definition-source
90   ;; Pathname of the source file that the definition was compiled from.
91   ;; This is null if the definition was not compiled from a file.
92   (pathname nil :type (or null pathname))
93   ;; Source-path of the definition within the file.
94   ;; This may be incomplete depending on the debug level at which the
95   ;; source was compiled.
96   (form-path '() :type list)
97   ;; Character offset of the top-level-form containing the definition.
98   ;; This corresponds to the first element of form-path.
99   (character-offset nil :type (or null integer))
100   ;; File-write-date of the source file when compiled.
101   ;; Null if not compiled from a file.
102   (file-write-date nil :type (or null integer))
103   ;; plist from WITH-COMPILATION-UNIT
104   (plist nil)
105   ;; Any extra metadata that the caller might be interested in. For
106   ;; example the specializers of the method whose definition-source this
107   ;; is.
108   (description nil :type list))
109
110 (defun find-definition-sources-by-name (name type)
111   "Returns a list of DEFINITION-SOURCEs for the objects of type TYPE
112 defined with name NAME. NAME may be a symbol or a extended function
113 name. Type can currently be one of the following:
114
115    (Public)
116    :CLASS
117    :COMPILER-MACRO
118    :CONDITION
119    :CONSTANT
120    :FUNCTION
121    :GENERIC-FUNCTION
122    :MACRO
123    :METHOD
124    :METHOD-COMBINATION
125    :PACKAGE
126    :SETF-EXPANDER
127    :STRUCTURE
128    :SYMBOL-MACRO
129    :TYPE
130    :VARIABLE
131
132    (Internal)
133    :OPTIMIZER
134    :SOURCE-TRANSFORM
135    :TRANSFORM
136    :VOP
137
138 If an unsupported TYPE is requested, the function will return NIL.
139 "
140   (flet ((listify (x)
141            (if (listp x)
142                x
143                (list x)))
144          (get-class (name)
145            (and (symbolp name)
146                 (find-class name nil))))
147     (listify
148      (case type
149        ((:variable)
150         (when (and (symbolp name)
151                    (eq (sb-int:info :variable :kind name) :special))
152           (translate-source-location (sb-int:info :source-location type name))))
153        ((:constant)
154         (when (and (symbolp name)
155                    (eq (sb-int:info :variable :kind name) :constant))
156           (translate-source-location (sb-int:info :source-location type name))))
157        ((:symbol-macro)
158         (when (and (symbolp name)
159                    (eq (sb-int:info :variable :kind name) :macro))
160           (translate-source-location (sb-int:info :source-location type name))))
161        ((:macro)
162         (when (and (symbolp name)
163                    (macro-function name))
164           (find-definition-source (macro-function name))))
165        ((:compiler-macro)
166         (when (compiler-macro-function name)
167           (find-definition-source (compiler-macro-function name))))
168        ((:function :generic-function)
169         (when (and (fboundp name)
170                    (or (not (symbolp name))
171                        (not (macro-function name))))
172           (let ((fun (fdefinition name)))
173             (when (eq (not (typep fun 'generic-function))
174                       (not (eq type :generic-function)))
175               (find-definition-source fun)))))
176        ((:type)
177         (let ((expander-fun (sb-int:info :type :expander name)))
178           (when expander-fun
179             (find-definition-source expander-fun))))
180        ((:method)
181         (when (and (fboundp name)
182                    (typep (fdefinition name) 'generic-function))
183           (loop for method in (sb-mop::generic-function-methods
184                                (fdefinition name))
185                 for source = (find-definition-source method)
186                 when source collect source)))
187        ((:setf-expander)
188         (when (and (consp name)
189                    (eq (car name) 'setf))
190           (setf name (cadr name)))
191         (let ((expander (or (sb-int:info :setf :inverse name)
192                             (sb-int:info :setf :expander name))))
193           (when expander
194             (sb-introspect:find-definition-source (if (symbolp expander)
195                                                       (symbol-function expander)
196                                                       expander)))))
197        ((:structure)
198         (let ((class (get-class name)))
199           (if class
200               (when (typep class 'sb-pcl::structure-class)
201                 (find-definition-source class))
202               (when (sb-int:info :typed-structure :info name)
203                 (translate-source-location
204                  (sb-int:info :source-location :typed-structure name))))))
205        ((:condition :class)
206         (let ((class (get-class name)))
207           (when (and class
208                      (not (typep class 'sb-pcl::structure-class)))
209             (when (eq (not (typep class 'sb-pcl::condition-class))
210                       (not (eq type :condition)))
211               (find-definition-source class)))))
212        ((:method-combination)
213         (let ((combination-fun
214                (ignore-errors (find-method #'sb-mop:find-method-combination
215                                            nil
216                                            (list (find-class 'generic-function)
217                                                  (list 'eql name)
218                                                  t)))))
219           (when combination-fun
220             (find-definition-source combination-fun))))
221        ((:package)
222         (when (symbolp name)
223           (let ((package (find-package name)))
224             (when package
225               (find-definition-source package)))))
226        ;; TRANSFORM and OPTIMIZER handling from swank-sbcl
227        ((:transform)
228         (when (symbolp name)
229           (let ((fun-info (sb-int:info :function :info name)))
230             (when fun-info
231               (loop for xform in (sb-c::fun-info-transforms fun-info)
232                     for source = (find-definition-source
233                                   (sb-c::transform-function xform))
234                     for typespec = (sb-kernel:type-specifier
235                                     (sb-c::transform-type xform))
236                     for note = (sb-c::transform-note xform)
237                     do (setf (definition-source-description source)
238                              (if (consp typespec)
239                                  (list (second typespec) note)
240                                  (list note)))
241                     collect source)))))
242        ((:optimizer)
243         (when (symbolp name)
244           (let ((fun-info (sb-int:info :function :info name)))
245             (when fun-info
246               (let ((otypes '((sb-c::fun-info-derive-type . sb-c:derive-type)
247                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
248                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
249                               (sb-c::fun-info-optimizer . sb-c:optimizer))))
250                 (loop for (reader . name) in otypes
251                       for fn = (funcall reader fun-info)
252                       when fn collect
253                       (let ((source (find-definition-source fn)))
254                         (setf (definition-source-description source)
255                               (list name))
256                         source)))))))
257        ((:vop)
258         (when (symbolp name)
259           (let ((fun-info (sb-int:info :function :info name)))
260             (when fun-info
261               (loop for vop in (sb-c::fun-info-templates fun-info)
262                     for source = (find-definition-source
263                                   (sb-c::vop-info-generator-function vop))
264                     do (setf (definition-source-description source)
265                              (list (sb-c::template-name vop)
266                                    (sb-c::template-note vop)))
267                     collect source)))))
268        ((:source-transform)
269         (when (symbolp name)
270           (let ((transform-fun (sb-int:info :function :source-transform name)))
271             (when transform-fun
272               (sb-introspect:find-definition-source transform-fun)))))
273        (t
274         nil)))))
275
276 (defun find-definition-source (object)
277   (typecase object
278     ((or sb-pcl::condition-class sb-pcl::structure-class)
279      (let ((classoid (sb-impl::find-classoid (class-name object))))
280        (when classoid
281          (let ((layout (sb-impl::classoid-layout classoid)))
282            (when layout
283              (translate-source-location
284               (sb-kernel::layout-source-location layout)))))))
285     (method-combination
286      (car
287       (find-definition-sources-by-name (sb-pcl::method-combination-type object)
288                                        :method-combination)))
289     (package
290      (translate-source-location (sb-impl::package-source-location object)))
291     (class
292      (translate-source-location (sb-pcl::definition-source object)))
293     ;; Use the PCL definition location information instead of the function
294     ;; debug-info for methods and generic functions. Sometimes the
295     ;; debug-info would point into PCL internals instead of the proper
296     ;; location.
297     (generic-function
298      (let ((source (translate-source-location
299                     (sb-pcl::definition-source object))))
300        (when source
301          (setf (definition-source-description source)
302                (list (sb-mop:generic-function-lambda-list object))))
303        source))
304     (method
305      (let ((source (translate-source-location
306                     (sb-pcl::definition-source object))))
307        (when source
308          (setf (definition-source-description source)
309                (append (method-qualifiers object)
310                        (sb-pcl::unparse-specializers
311                         (sb-mop:method-specializers object)))))
312        source))
313     (function
314      (cond ((struct-accessor-p object)
315             (find-definition-source
316              (struct-accessor-structure-class object)))
317            ((struct-predicate-p object)
318             (find-definition-source
319              (struct-predicate-structure-class object)))
320            (t
321             (find-function-definition-source object))))
322     (t
323      (error "Don't know how to retrive source location for a ~S~%"
324             (type-of object)))))
325
326 (defun find-function-definition-source (function)
327   (let* ((debug-info (function-debug-info function))
328          (debug-source (debug-info-source debug-info))
329          (debug-fun (debug-info-debug-function debug-info))
330          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
331     (make-definition-source
332      :pathname
333      (if (eql (sb-c::debug-source-from debug-source) :file)
334          (parse-namestring (sb-c::debug-source-name debug-source)))
335      :character-offset
336      (if tlf
337          (elt (sb-c::debug-source-start-positions debug-source) tlf))
338      ;; Unfortunately there is no proper source path available in the
339      ;; debug-source. FIXME: We could use sb-di:code-locations to get
340      ;; a full source path. -luke (12/Mar/2005)
341      :form-path (if tlf (list tlf))
342      :file-write-date (sb-c::debug-source-created debug-source)
343      :plist (sb-c::debug-source-plist debug-source))))
344
345 (defun translate-source-location (location)
346   (if location
347       (make-definition-source
348        :pathname (let ((n (sb-c:definition-source-location-namestring location)))
349                    (when n
350                      (parse-namestring n)))
351        :form-path
352        (let ((number (sb-c:definition-source-location-toplevel-form-number
353                          location)))
354          (when number
355            (list number)))
356        :plist (sb-c:definition-source-location-plist location))
357       (make-definition-source)))
358
359 ;;; This is kludgey.  We expect these functions (the underlying functions,
360 ;;; not the closures) to be in static space and so not move ever.
361 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
362 ;;; accessors, e.g. when the :type option is used
363 (defvar *struct-slotplace-reader*
364   (sb-vm::%simple-fun-self #'definition-source-pathname))
365 (defvar *struct-slotplace-writer*
366   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
367 (defvar *struct-predicate*
368   (sb-vm::%simple-fun-self #'definition-source-p))
369
370 (defun struct-accessor-p (function)
371   (let ((self (sb-vm::%simple-fun-self function)))
372     ;; FIXME there are other kinds of struct accessor.  Fill out this list
373     (member self (list *struct-slotplace-reader*
374                        *struct-slotplace-writer*))))
375
376 (defun struct-predicate-p (function)
377   (let ((self (sb-vm::%simple-fun-self function)))
378     ;; FIXME there may be other structure predicate functions
379     (member self (list *struct-predicate*))))
380
381 ;;; FIXME: maybe this should be renamed as FUNCTION-LAMBDA-LIST?
382 (defun function-arglist (function)
383   "Describe the lambda list for the function designator FUNCTION.
384 Works for special-operators, macros, simple functions and generic
385 functions.  Signals error if not found"
386   (cond ((valid-function-name-p function)
387          (function-arglist
388           (or (macro-function function) (fdefinition function))))
389         ((typep function 'generic-function)
390          (sb-pcl::generic-function-pretty-arglist function))
391         (t (sb-impl::%simple-fun-arglist
392             (sb-impl::%closure-fun function)))))
393
394 (defun struct-accessor-structure-class (function)
395   (let ((self (sb-vm::%simple-fun-self function)))
396     (cond
397       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
398        (find-class
399         (sb-kernel::classoid-name
400          (sb-kernel::layout-classoid
401           (sb-kernel:%closure-index-ref function 1)))))
402       )))
403
404 (defun struct-predicate-structure-class (function)
405   (let ((self (sb-vm::%simple-fun-self function)))
406     (cond
407       ((member self (list *struct-predicate*))
408        (find-class
409         (sb-kernel::classoid-name
410          (sb-kernel::layout-classoid
411           (sb-kernel:%closure-index-ref function 0)))))
412       )))
413
414 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
415
416 ;;; This interface is trmendously experimental.
417
418 ;;; For the moment I'm taking the view that FDEFN is an internal
419 ;;; object (one out of one CMUCL developer surveyed didn't know what
420 ;;; they were for), so these routines deal in FUNCTIONs
421
422 ;;; Find callers and callees by looking at the constant pool of
423 ;;; compiled code objects.  We assume every fdefn object in the
424 ;;; constant pool corresponds to a call to that function.  A better
425 ;;; strategy would be to use the disassembler to find actual
426 ;;; call-sites.
427
428 (defun find-function-callees (function)
429   "Return functions called by FUNCTION."
430   (let ((callees '()))
431     (map-code-constants
432      (sb-kernel:fun-code-header function)
433      (lambda (obj)
434        (when (sb-kernel:fdefn-p obj)
435          (push (sb-kernel:fdefn-fun obj)
436                callees))))
437     callees))
438
439
440 (defun find-function-callers (function &optional (spaces '(:read-only :static
441                                                            :dynamic)))
442   "Return functions which call FUNCTION, by searching SPACES for code objects"
443   (let ((referrers '()))
444     (map-caller-code-components
445      function
446      spaces
447      (lambda (code)
448        (let ((entry (sb-kernel:%code-entry-points  code)))
449          (cond ((not entry)
450                 (push (princ-to-string code) referrers))
451                (t
452                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
453                       while e
454                       do (pushnew e referrers)))))))
455     referrers))
456
457 (declaim (inline map-code-constants))
458 (defun map-code-constants (code fn)
459   "Call FN for each constant in CODE's constant pool."
460   (check-type code sb-kernel:code-component)
461   (loop for i from sb-vm:code-constants-offset below
462         (sb-kernel:get-header-data code)
463         do (funcall fn (sb-kernel:code-header-ref code i))))
464
465 (declaim (inline map-allocated-code-components))
466 (defun map-allocated-code-components (spaces fn)
467   "Call FN for each allocated code component in one of SPACES.  FN
468 receives the object and its size as arguments.  SPACES should be a
469 list of the symbols :dynamic, :static, or :read-only."
470   (dolist (space spaces)
471     (sb-vm::map-allocated-objects
472      (lambda (obj header size)
473        (when (= sb-vm:code-header-widetag header)
474          (funcall fn obj size)))
475      space)))
476
477 (declaim (inline map-caller-code-components))
478 (defun map-caller-code-components (function spaces fn)
479   "Call FN for each code component with a fdefn for FUNCTION in its
480 constant pool."
481   (let ((function (coerce function 'function)))
482     (map-allocated-code-components
483      spaces
484      (lambda (obj size)
485        (declare (ignore size))
486        (map-code-constants
487         obj
488         (lambda (constant)
489           (when (and (sb-kernel:fdefn-p constant)
490                      (eq (sb-kernel:fdefn-fun constant)
491                          function))
492             (funcall fn obj))))))))
493
494 (provide 'sb-introspect)