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