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