0.9.6.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 ;;; 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   (listify
145    (case type
146      ((:variable)
147       (when (eq (sb-int:info :variable :kind name) :special)
148         (translate-source-location (sb-int:info :source-location type name))))
149      ((:constant)
150       (when (eq (sb-int:info :variable :kind name) :constant)
151         (translate-source-location (sb-int:info :source-location type name))))
152      ((:symbol-macro)
153       (when (eq (sb-int:info :variable :kind name) :macro)
154         (translate-source-location (sb-int:info :source-location type name))))
155      ((:macro)
156       (when (and (symbolp name)
157                  (macro-function name))
158         (find-definition-source (macro-function name))))
159      ((:compiler-macro)
160       (when (compiler-macro-function name)
161         (find-definition-source (compiler-macro-function name))))
162      ((:function :generic-function)
163       (when (and (fboundp name)
164                  (or (not (symbolp name))
165                      (not (macro-function name))))
166         (let ((fun (fdefinition name)))
167           (when (eq (not (typep fun 'generic-function))
168                     (not (eq type :generic-function)))
169             (find-definition-source fun)))))
170      ((:type)
171       (let ((expander-fun (sb-int:info :type :expander name)))
172         (when expander-fun
173           (find-definition-source expander-fun))))
174      ((:method)
175       (when (and (fboundp name)
176                  (typep (fdefinition name) 'generic-function))
177         (loop for method in (sb-mop::generic-function-methods
178                              (fdefinition name))
179               for source = (find-definition-source method)
180               when source collect source)))
181      ((:setf-expander)
182       (when (and (consp name)
183                  (eq (car name) 'setf))
184         (setf name (cadr name)))
185       (let ((expander-fun (or (sb-int:info :setf :inverse name)
186                               (sb-int:info :setf :expander name))))
187         (when expander-fun
188           (sb-introspect:find-definition-source expander-fun))))
189      ((:structure)
190       (let ((class (ignore-errors (find-class name))))
191         (if class
192             (when (typep class 'sb-pcl::structure-class)
193               (find-definition-source class))
194             (when (sb-int:info :typed-structure :info name)
195               (translate-source-location
196                (sb-int:info :source-location :typed-structure name))))))
197      ((:condition :class)
198       (let ((class (ignore-errors (find-class name))))
199         (when class
200           (when (eq (not (typep class 'sb-pcl::condition-class))
201                     (not (eq type :condition)))
202             (find-definition-source class)))))
203      ((:method-combination)
204       (let ((combination-fun
205              (ignore-errors (find-method #'sb-mop:find-method-combination
206                                          nil
207                                          (list (find-class 'generic-function)
208                                                (list 'eql name)
209                                                t)))))
210         (when combination-fun
211           (find-definition-source combination-fun))))
212      ((:package)
213       (when (symbolp name)
214         (let ((package (find-package name)))
215           (when package
216             (find-definition-source package)))))
217      ;;; TRANSFORM and OPTIMIZER handling from swank-sbcl
218      ((:transform)
219       (let ((fun-info (sb-int:info :function :info name)))
220         (when fun-info
221           (loop for xform in (sb-c::fun-info-transforms fun-info)
222                 for source = (find-definition-source
223                               (sb-c::transform-function xform))
224                 for typespec = (sb-kernel:type-specifier
225                                 (sb-c::transform-type xform))
226                 for note = (sb-c::transform-note xform)
227                 do (setf (definition-source-description source)
228                          (if (consp typespec)
229                              (list (second typespec) note)
230                              (list note)))
231                 collect source))))
232      ((:optimizer)
233       (let ((fun-info (sb-int:info :function :info name)))
234         (when fun-info
235           (let ((otypes '((sb-c::fun-info-derive-type . sb-c:derive-type)
236                           (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
237                           (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
238                           (sb-c::fun-info-optimizer . sb-c:optimizer))))
239             (loop for (reader . name) in otypes
240                   for fn = (funcall reader fun-info)
241                   when fn collect
242                   (let ((source (find-definition-source fn)))
243                     (setf (definition-source-description source)
244                           (list name))
245                     source))))))
246      ((:vop)
247       (let ((fun-info (sb-int:info :function :info name)))
248         (when fun-info
249           (loop for vop in (sb-c::fun-info-templates fun-info)
250                 for source = (find-definition-source
251                               (sb-c::vop-info-generator-function vop))
252                 do (setf (definition-source-description source)
253                          (list (sb-c::template-name vop)
254                                (sb-c::template-note vop)))
255                 collect source))))
256      ((:source-transform)
257       (let ((transform-fun (sb-int:info :function :source-transform name)))
258         (when transform-fun
259           (sb-introspect:find-definition-source transform-fun))))
260      (t
261       nil)))))
262
263 (defun find-definition-source (object)
264   (typecase object
265     ((or sb-pcl::condition-class sb-pcl::structure-class)
266      (let ((classoid (sb-impl::find-classoid (class-name object))))
267        (when classoid
268          (let ((layout (sb-impl::classoid-layout classoid)))
269            (when layout
270              (translate-source-location
271               (sb-kernel::layout-source-location layout)))))))
272     (method-combination
273      (car
274       (find-definition-sources-by-name (sb-pcl::method-combination-type object)
275                                        :method-combination)))
276     (package
277      (translate-source-location (sb-impl::package-source-location object)))
278     (class
279      (translate-source-location (sb-pcl::definition-source object)))
280     ;; Use the PCL definition location information instead of the function
281     ;; debug-info for methods and generic functions. Sometimes the
282     ;; debug-info would point into PCL internals instead of the proper
283     ;; location.
284     (generic-function
285      (let ((source (translate-source-location
286                     (sb-pcl::definition-source object))))
287        (when source
288          (setf (definition-source-description source)
289                (list (sb-mop:generic-function-lambda-list object))))
290        source))
291     (method
292      (let ((source (translate-source-location
293                     (sb-pcl::definition-source object))))
294        (when source
295          (setf (definition-source-description source)
296                (append (method-qualifiers object)
297                        (sb-pcl::unparse-specializers
298                         (sb-mop:method-specializers object)))))
299        source))
300     (function
301      (cond ((struct-accessor-p object)
302             (find-definition-source
303              (struct-accessor-structure-class object)))
304            ((struct-predicate-p object)
305             (find-definition-source
306              (struct-predicate-structure-class object)))
307            (t
308             (find-function-definition-source object))))
309     (t
310      (error "Don't know how to retrive source location for a ~S~%"
311             (type-of object)))))
312
313 (defun find-function-definition-source (function)
314   (let* ((debug-info (function-debug-info function))
315          (debug-source (debug-info-source debug-info))
316          (debug-fun (debug-info-debug-function debug-info))
317          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
318     (make-definition-source
319      :pathname
320      (if (eql (sb-c::debug-source-from debug-source) :file)
321          (parse-namestring (sb-c::debug-source-name debug-source)))
322      :character-offset
323      (if tlf
324          (elt (sb-c::debug-source-start-positions debug-source) tlf))
325      ;; Unfortunately there is no proper source path available in the
326      ;; debug-source. FIXME: We could use sb-di:code-locations to get
327      ;; a full source path. -luke (12/Mar/2005)
328      :form-path (if tlf (list tlf))
329      :file-write-date (sb-c::debug-source-created debug-source)
330      :plist (sb-c::debug-source-plist debug-source))))
331
332 (defun translate-source-location (location)
333   (if location
334       (make-definition-source
335        :pathname (let ((n (sb-c:definition-source-location-namestring location)))
336                    (when n
337                      (parse-namestring n)))
338        :form-path
339        (let ((number (sb-c:definition-source-location-toplevel-form-number
340                          location)))
341          (when number
342            (list number)))
343        :plist (sb-c:definition-source-location-plist location))
344       (make-definition-source)))
345
346 ;;; This is kludgey.  We expect these functions (the underlying functions,
347 ;;; not the closures) to be in static space and so not move ever.
348 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
349 ;;; accessors, e.g. when the :type option is used
350 (defvar *struct-slotplace-reader*
351   (sb-vm::%simple-fun-self #'definition-source-pathname))
352 (defvar *struct-slotplace-writer*
353   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
354 (defvar *struct-predicate*
355   (sb-vm::%simple-fun-self #'definition-source-p))
356
357 (defun struct-accessor-p (function)
358   (let ((self (sb-vm::%simple-fun-self function)))
359     ;; FIXME there are other kinds of struct accessor.  Fill out this list
360     (member self (list *struct-slotplace-reader*
361                        *struct-slotplace-writer*))))
362
363 (defun struct-predicate-p (function)
364   (let ((self (sb-vm::%simple-fun-self function)))
365     ;; FIXME there may be other structure predicate functions
366     (member self (list *struct-predicate*))))
367
368 ;;; FIXME: maybe this should be renamed as FUNCTION-LAMBDA-LIST?
369 (defun function-arglist (function)
370   "Describe the lambda list for the function designator FUNCTION.
371 Works for special-operators, macros, simple functions and generic
372 functions.  Signals error if not found"
373   (cond ((valid-function-name-p function)
374          (function-arglist
375           (or (macro-function function) (fdefinition function))))
376         ((typep function 'generic-function)
377          (sb-pcl::generic-function-pretty-arglist function))
378         (t (sb-impl::%simple-fun-arglist
379             (sb-impl::%closure-fun function)))))
380
381 (defun struct-accessor-structure-class (function)
382   (let ((self (sb-vm::%simple-fun-self function)))
383     (cond
384       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
385        (find-class
386         (sb-kernel::classoid-name
387          (sb-kernel::layout-classoid
388           (sb-kernel:%closure-index-ref function 1)))))
389       )))
390
391 (defun struct-predicate-structure-class (function)
392   (let ((self (sb-vm::%simple-fun-self function)))
393     (cond
394       ((member self (list *struct-predicate*))
395        (find-class
396         (sb-kernel::classoid-name
397          (sb-kernel::layout-classoid
398           (sb-kernel:%closure-index-ref function 0)))))
399       )))
400
401 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
402
403 ;;; This interface is trmendously experimental.
404
405 ;;; For the moment I'm taking the view that FDEFN is an internal
406 ;;; object (one out of one CMUCL developer surveyed didn't know what
407 ;;; they were for), so these routines deal in FUNCTIONs
408
409 ;;; Find callers and callees by looking at the constant pool of
410 ;;; compiled code objects.  We assume every fdefn object in the
411 ;;; constant pool corresponds to a call to that function.  A better
412 ;;; strategy would be to use the disassembler to find actual
413 ;;; call-sites.
414
415 (defun find-function-callees (function)
416   "Return functions called by FUNCTION."
417   (let ((callees '()))
418     (map-code-constants
419      (sb-kernel:fun-code-header function)
420      (lambda (obj)
421        (when (sb-kernel:fdefn-p obj)
422          (push (sb-kernel:fdefn-fun obj)
423                callees))))
424     callees))
425
426
427 (defun find-function-callers (function &optional (spaces '(:read-only :static
428                                                            :dynamic)))
429   "Return functions which call FUNCTION, by searching SPACES for code objects"
430   (let ((referrers '()))
431     (map-caller-code-components
432      function
433      spaces
434      (lambda (code)
435        (let ((entry (sb-kernel:%code-entry-points  code)))
436          (cond ((not entry)
437                 (push (princ-to-string code) referrers))
438                (t
439                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
440                       while e
441                       do (pushnew e referrers)))))))
442     referrers))
443
444 (declaim (inline map-code-constants))
445 (defun map-code-constants (code fn)
446   "Call FN for each constant in CODE's constant pool."
447   (check-type code sb-kernel:code-component)
448   (loop for i from sb-vm:code-constants-offset below
449         (sb-kernel:get-header-data code)
450         do (funcall fn (sb-kernel:code-header-ref code i))))
451
452 (declaim (inline map-allocated-code-components))
453 (defun map-allocated-code-components (spaces fn)
454   "Call FN for each allocated code component in one of SPACES.  FN
455 receives the object and its size as arguments.  SPACES should be a
456 list of the symbols :dynamic, :static, or :read-only."
457   (dolist (space spaces)
458     (sb-vm::map-allocated-objects
459      (lambda (obj header size)
460        (when (= sb-vm:code-header-widetag header)
461          (funcall fn obj size)))
462      space)))
463
464 (declaim (inline map-caller-code-components))
465 (defun map-caller-code-components (function spaces fn)
466   "Call FN for each code component with a fdefn for FUNCTION in its
467 constant pool."
468   (let ((function (coerce function 'function)))
469     (map-allocated-code-components
470      spaces
471      (lambda (obj size)
472        (declare (ignore size))
473        (map-code-constants
474         obj
475         (lambda (constant)
476           (when (and (sb-kernel:fdefn-p constant)
477                      (eq (sb-kernel:fdefn-fun constant)
478                          function))
479             (funcall fn obj))))))))
480
481 (provide 'sb-introspect)