b163ba639312344560c21030d510f495821b0faa
[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            "WHO-BINDS"
41            "WHO-CALLS"
42            "WHO-REFERENCES"
43            "WHO-SETS"
44            "WHO-MACROEXPANDS"))
45
46 (in-package :sb-introspect)
47
48 ;;;; Internal interface for SBCL debug info
49
50 ;;; Here are some tutorial-style type definitions to help understand
51 ;;; the internal SBCL debugging data structures we're using. The
52 ;;; commentary is based on CMUCL's debug internals manual.
53 ;;;
54 (deftype debug-info ()
55   "Structure containing all the debug information related to a function.
56 Function objects reference debug-infos which in turn reference
57 debug-sources and so on."
58   'sb-c::compiled-debug-info)
59
60 (deftype debug-source ()
61   "Debug sources describe where to find source code.
62 For example, the debug source for a function compiled from a file will
63 include the pathname of the file and the position of the definition."
64   'sb-c::debug-source)
65
66 (deftype debug-function ()
67   "Debug function represent static compile-time information about a function."
68   'sb-c::compiled-debug-fun)
69
70 (declaim (ftype (function (function) debug-info) function-debug-info))
71 (defun function-debug-info (function)
72   (let* ((function-object (sb-kernel::%closure-fun function))
73          (function-header (sb-kernel:fun-code-header function-object)))
74     (sb-kernel:%code-debug-info function-header)))
75
76 (declaim (ftype (function (function) debug-source) function-debug-source))
77 (defun function-debug-source (function)
78   (debug-info-source (function-debug-info function)))
79
80 (declaim (ftype (function (debug-info) debug-source) debug-info-source))
81 (defun debug-info-source (debug-info)
82   (sb-c::debug-info-source debug-info))
83
84 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
85 (defun debug-info-debug-function (debug-info)
86   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
87
88 (defun valid-function-name-p (name)
89   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
90   (and (sb-int:valid-function-name-p name) t))
91
92 ;;;; Finding definitions
93
94 (defstruct definition-source
95   ;; Pathname of the source file that the definition was compiled from.
96   ;; This is null if the definition was not compiled from a file.
97   (pathname nil :type (or null pathname))
98   ;; Source-path of the definition within the file.
99   ;; This may be incomplete depending on the debug level at which the
100   ;; source was compiled.
101   (form-path '() :type list)
102   ;; Character offset of the top-level-form containing the definition.
103   ;; This corresponds to the first element of form-path.
104   (character-offset nil :type (or null integer))
105   ;; File-write-date of the source file when compiled.
106   ;; Null if not compiled from a file.
107   (file-write-date nil :type (or null integer))
108   ;; plist from WITH-COMPILATION-UNIT
109   (plist nil)
110   ;; Any extra metadata that the caller might be interested in. For
111   ;; example the specializers of the method whose definition-source this
112   ;; is.
113   (description nil :type list))
114
115 (defun find-definition-sources-by-name (name type)
116   "Returns a list of DEFINITION-SOURCEs for the objects of type TYPE
117 defined with name NAME. NAME may be a symbol or a extended function
118 name. Type can currently be one of the following:
119
120    (Public)
121    :CLASS
122    :COMPILER-MACRO
123    :CONDITION
124    :CONSTANT
125    :FUNCTION
126    :GENERIC-FUNCTION
127    :MACRO
128    :METHOD
129    :METHOD-COMBINATION
130    :PACKAGE
131    :SETF-EXPANDER
132    :STRUCTURE
133    :SYMBOL-MACRO
134    :TYPE
135    :VARIABLE
136
137    (Internal)
138    :OPTIMIZER
139    :SOURCE-TRANSFORM
140    :TRANSFORM
141    :VOP
142
143 If an unsupported TYPE is requested, the function will return NIL.
144 "
145   (flet ((listify (x)
146            (if (listp x)
147                x
148                (list x)))
149          (get-class (name)
150            (and (symbolp name)
151                 (find-class name nil)))
152          (real-fdefinition (name)
153            ;; for getting the real function object, even if the
154            ;; function is being profiled
155            (let ((profile-info (gethash name sb-profile::*profiled-fun-name->info*)))
156              (if profile-info
157                  (sb-profile::profile-info-encapsulated-fun profile-info)
158                  (fdefinition name)))))
159     (listify
160      (case type
161        ((:variable)
162         (when (and (symbolp name)
163                    (eq (sb-int:info :variable :kind name) :special))
164           (translate-source-location (sb-int:info :source-location type name))))
165        ((:constant)
166         (when (and (symbolp name)
167                    (eq (sb-int:info :variable :kind name) :constant))
168           (translate-source-location (sb-int:info :source-location type name))))
169        ((:symbol-macro)
170         (when (and (symbolp name)
171                    (eq (sb-int:info :variable :kind name) :macro))
172           (translate-source-location (sb-int:info :source-location type name))))
173        ((:macro)
174         (when (and (symbolp name)
175                    (macro-function name))
176           (find-definition-source (macro-function name))))
177        ((:compiler-macro)
178         (when (compiler-macro-function name)
179           (find-definition-source (compiler-macro-function name))))
180        ((:function :generic-function)
181         (when (and (fboundp name)
182                    (or (not (symbolp name))
183                        (not (macro-function name))))
184           (let ((fun (real-fdefinition name)))
185             (when (eq (not (typep fun 'generic-function))
186                       (not (eq type :generic-function)))
187               (find-definition-source fun)))))
188        ((:type)
189         ;; Source locations for types are saved separately when the expander
190         ;; is a closure without a good source-location.
191         (let ((loc (sb-int:info :type :source-location name)))
192           (if loc
193               (translate-source-location loc)
194               (let ((expander-fun (sb-int:info :type :expander name)))
195                 (when expander-fun
196                   (find-definition-source expander-fun))))))
197        ((:method)
198         (when (fboundp name)
199           (let ((fun (real-fdefinition name)))
200            (when (typep fun 'generic-function)
201              (loop for method in (sb-mop::generic-function-methods
202                                   fun)
203                 for source = (find-definition-source method)
204                 when source collect source)))))
205        ((:setf-expander)
206         (when (and (consp name)
207                    (eq (car name) 'setf))
208           (setf name (cadr name)))
209         (let ((expander (or (sb-int:info :setf :inverse name)
210                             (sb-int:info :setf :expander name))))
211           (when expander
212             (sb-introspect:find-definition-source (if (symbolp expander)
213                                                       (symbol-function expander)
214                                                       expander)))))
215        ((:structure)
216         (let ((class (get-class name)))
217           (if class
218               (when (typep class 'sb-pcl::structure-class)
219                 (find-definition-source class))
220               (when (sb-int:info :typed-structure :info name)
221                 (translate-source-location
222                  (sb-int:info :source-location :typed-structure name))))))
223        ((:condition :class)
224         (let ((class (get-class name)))
225           (when (and class
226                      (not (typep class 'sb-pcl::structure-class)))
227             (when (eq (not (typep class 'sb-pcl::condition-class))
228                       (not (eq type :condition)))
229               (find-definition-source class)))))
230        ((:method-combination)
231         (let ((combination-fun
232                (find-method #'sb-mop:find-method-combination
233                             nil
234                             (list (find-class 'generic-function)
235                                   (list 'eql name)
236                                   t)
237                             nil)))
238           (when combination-fun
239             (find-definition-source combination-fun))))
240        ((:package)
241         (when (symbolp name)
242           (let ((package (find-package name)))
243             (when package
244               (find-definition-source package)))))
245        ;; TRANSFORM and OPTIMIZER handling from swank-sbcl
246        ((:transform)
247         (when (symbolp name)
248           (let ((fun-info (sb-int:info :function :info name)))
249             (when fun-info
250               (loop for xform in (sb-c::fun-info-transforms fun-info)
251                     for source = (find-definition-source
252                                   (sb-c::transform-function xform))
253                     for typespec = (sb-kernel:type-specifier
254                                     (sb-c::transform-type xform))
255                     for note = (sb-c::transform-note xform)
256                     do (setf (definition-source-description source)
257                              (if (consp typespec)
258                                  (list (second typespec) note)
259                                  (list note)))
260                     collect source)))))
261        ((:optimizer)
262         (when (symbolp name)
263           (let ((fun-info (sb-int:info :function :info name)))
264             (when fun-info
265               (let ((otypes '((sb-c::fun-info-derive-type . sb-c:derive-type)
266                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
267                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
268                               (sb-c::fun-info-optimizer . sb-c:optimizer))))
269                 (loop for (reader . name) in otypes
270                       for fn = (funcall reader fun-info)
271                       when fn collect
272                       (let ((source (find-definition-source fn)))
273                         (setf (definition-source-description source)
274                               (list name))
275                         source)))))))
276        ((:vop)
277         (when (symbolp name)
278           (let ((fun-info (sb-int:info :function :info name)))
279             (when fun-info
280               (loop for vop in (sb-c::fun-info-templates fun-info)
281                     for source = (find-definition-source
282                                   (sb-c::vop-info-generator-function vop))
283                     do (setf (definition-source-description source)
284                              (list (sb-c::template-name vop)
285                                    (sb-c::template-note vop)))
286                     collect source)))))
287        ((:source-transform)
288         (when (symbolp name)
289           (let ((transform-fun (sb-int:info :function :source-transform name)))
290             (when transform-fun
291               (sb-introspect:find-definition-source transform-fun)))))
292        (t
293         nil)))))
294
295 (defun find-definition-source (object)
296   (typecase object
297     ((or sb-pcl::condition-class sb-pcl::structure-class)
298      (let ((classoid (sb-impl::find-classoid (class-name object))))
299        (when classoid
300          (let ((layout (sb-impl::classoid-layout classoid)))
301            (when layout
302              (translate-source-location
303               (sb-kernel::layout-source-location layout)))))))
304     (method-combination
305      (car
306       (find-definition-sources-by-name
307        (sb-pcl::method-combination-type-name object) :method-combination)))
308     (package
309      (translate-source-location (sb-impl::package-source-location object)))
310     (class
311      (translate-source-location (sb-pcl::definition-source object)))
312     ;; Use the PCL definition location information instead of the function
313     ;; debug-info for methods and generic functions. Sometimes the
314     ;; debug-info would point into PCL internals instead of the proper
315     ;; location.
316     (generic-function
317      (let ((source (translate-source-location
318                     (sb-pcl::definition-source object))))
319        (when source
320          (setf (definition-source-description source)
321                (list (sb-mop:generic-function-lambda-list object))))
322        source))
323     (method
324      (let ((source (translate-source-location
325                     (sb-pcl::definition-source object))))
326        (when source
327          (setf (definition-source-description source)
328                (append (method-qualifiers object)
329                        (if (sb-mop:method-generic-function object)
330                            (sb-pcl::unparse-specializers
331                             (sb-mop:method-generic-function object)
332                             (sb-mop:method-specializers object))
333                            (sb-mop:method-specializers object)))))
334        source))
335     #+sb-eval
336     (sb-eval:interpreted-function
337      (let ((source (translate-source-location
338                     (sb-eval:interpreted-function-source-location object))))
339        source))
340     (function
341      (cond ((struct-accessor-p object)
342             (find-definition-source
343              (struct-accessor-structure-class object)))
344            ((struct-predicate-p object)
345             (find-definition-source
346              (struct-predicate-structure-class object)))
347            (t
348             (find-function-definition-source object))))
349     ((or condition standard-object structure-object)
350      (find-definition-source (class-of object)))
351     (t
352      (error "Don't know how to retrieve source location for a ~S~%"
353             (type-of object)))))
354
355 (defun find-function-definition-source (function)
356   (let* ((debug-info (function-debug-info function))
357          (debug-source (debug-info-source debug-info))
358          (debug-fun (debug-info-debug-function debug-info))
359          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
360     (make-definition-source
361      :pathname
362      ;; KLUDGE: at the moment, we don't record the correct toplevel
363      ;; form number for forms processed by EVAL (including EVAL-WHEN
364      ;; :COMPILE-TOPLEVEL).  Until that's fixed, don't return a
365      ;; DEFINITION-SOURCE with a pathname.  (When that's fixed, take
366      ;; out the (not (debug-source-form ...)) test.
367      (if (and (sb-c::debug-source-namestring debug-source)
368               (not (sb-c::debug-source-form debug-source)))
369          (parse-namestring (sb-c::debug-source-namestring debug-source)))
370      :character-offset
371      (if tlf
372          (elt (sb-c::debug-source-start-positions debug-source) tlf))
373      ;; Unfortunately there is no proper source path available in the
374      ;; debug-source. FIXME: We could use sb-di:code-locations to get
375      ;; a full source path. -luke (12/Mar/2005)
376      :form-path (if tlf (list tlf))
377      :file-write-date (sb-c::debug-source-created debug-source)
378      :plist (sb-c::debug-source-plist debug-source))))
379
380 (defun translate-source-location (location)
381   (if location
382       (make-definition-source
383        :pathname (let ((n (sb-c:definition-source-location-namestring location)))
384                    (when n
385                      (parse-namestring n)))
386        :form-path
387        (let ((number (sb-c:definition-source-location-toplevel-form-number
388                          location)))
389          (when number
390            (list number)))
391        :plist (sb-c:definition-source-location-plist location))
392       (make-definition-source)))
393
394 ;;; This is kludgey.  We expect these functions (the underlying functions,
395 ;;; not the closures) to be in static space and so not move ever.
396 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
397 ;;; accessors, e.g. when the :type option is used
398 (defvar *struct-slotplace-reader*
399   (sb-vm::%simple-fun-self #'definition-source-pathname))
400 (defvar *struct-slotplace-writer*
401   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
402 (defvar *struct-predicate*
403   (sb-vm::%simple-fun-self #'definition-source-p))
404
405 (defun struct-accessor-p (function)
406   (let ((self (sb-vm::%simple-fun-self function)))
407     ;; FIXME there are other kinds of struct accessor.  Fill out this list
408     (member self (list *struct-slotplace-reader*
409                        *struct-slotplace-writer*))))
410
411 (defun struct-predicate-p (function)
412   (let ((self (sb-vm::%simple-fun-self function)))
413     ;; FIXME there may be other structure predicate functions
414     (member self (list *struct-predicate*))))
415
416 ;;; FIXME: maybe this should be renamed as FUNCTION-LAMBDA-LIST?
417 (defun function-arglist (function)
418   "Describe the lambda list for the extended function designator FUNCTION.
419 Works for special-operators, macros, simple functions,
420 interpreted functions, and generic functions.  Signals error if
421 not found"
422   (cond ((valid-function-name-p function)
423          (function-arglist (or (and (symbolp function)
424                                     (macro-function function))
425                                (fdefinition function))))
426         ((typep function 'generic-function)
427          (sb-pcl::generic-function-pretty-arglist function))
428         #+sb-eval
429         ((typep function 'sb-eval:interpreted-function)
430          (sb-eval:interpreted-function-lambda-list function))
431         (t (sb-kernel:%simple-fun-arglist (sb-kernel:%fun-fun function)))))
432
433 (defun struct-accessor-structure-class (function)
434   (let ((self (sb-vm::%simple-fun-self function)))
435     (cond
436       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
437        (find-class
438         (sb-kernel::classoid-name
439          (sb-kernel::layout-classoid
440           (sb-kernel:%closure-index-ref function 1)))))
441       )))
442
443 (defun struct-predicate-structure-class (function)
444   (let ((self (sb-vm::%simple-fun-self function)))
445     (cond
446       ((member self (list *struct-predicate*))
447        (find-class
448         (sb-kernel::classoid-name
449          (sb-kernel::layout-classoid
450           (sb-kernel:%closure-index-ref function 0)))))
451       )))
452
453 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
454
455 ;;; This interface is trmendously experimental.
456
457 ;;; For the moment I'm taking the view that FDEFN is an internal
458 ;;; object (one out of one CMUCL developer surveyed didn't know what
459 ;;; they were for), so these routines deal in FUNCTIONs
460
461 ;;; Find callers and callees by looking at the constant pool of
462 ;;; compiled code objects.  We assume every fdefn object in the
463 ;;; constant pool corresponds to a call to that function.  A better
464 ;;; strategy would be to use the disassembler to find actual
465 ;;; call-sites.
466
467 (defun find-function-callees (function)
468   "Return functions called by FUNCTION."
469   (let ((callees '()))
470     (map-code-constants
471      (sb-kernel:fun-code-header function)
472      (lambda (obj)
473        (when (sb-kernel:fdefn-p obj)
474          (push (sb-kernel:fdefn-fun obj)
475                callees))))
476     callees))
477
478
479 (defun find-function-callers (function &optional (spaces '(:read-only :static
480                                                            :dynamic)))
481   "Return functions which call FUNCTION, by searching SPACES for code objects"
482   (let ((referrers '()))
483     (map-caller-code-components
484      function
485      spaces
486      (lambda (code)
487        (let ((entry (sb-kernel:%code-entry-points  code)))
488          (cond ((not entry)
489                 (push (princ-to-string code) referrers))
490                (t
491                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
492                       while e
493                       do (pushnew e referrers)))))))
494     referrers))
495
496 (declaim (inline map-code-constants))
497 (defun map-code-constants (code fn)
498   "Call FN for each constant in CODE's constant pool."
499   (check-type code sb-kernel:code-component)
500   (loop for i from sb-vm:code-constants-offset below
501         (sb-kernel:get-header-data code)
502         do (funcall fn (sb-kernel:code-header-ref code i))))
503
504 (declaim (inline map-allocated-code-components))
505 (defun map-allocated-code-components (spaces fn)
506   "Call FN for each allocated code component in one of SPACES.  FN
507 receives the object and its size as arguments.  SPACES should be a
508 list of the symbols :dynamic, :static, or :read-only."
509   (dolist (space spaces)
510     (sb-vm::map-allocated-objects
511      (lambda (obj header size)
512        (when (= sb-vm:code-header-widetag header)
513          (funcall fn obj size)))
514      space
515      t)))
516
517 (declaim (inline map-caller-code-components))
518 (defun map-caller-code-components (function spaces fn)
519   "Call FN for each code component with a fdefn for FUNCTION in its
520 constant pool."
521   (let ((function (coerce function 'function)))
522     (map-allocated-code-components
523      spaces
524      (lambda (obj size)
525        (declare (ignore size))
526        (map-code-constants
527         obj
528         (lambda (constant)
529           (when (and (sb-kernel:fdefn-p constant)
530                      (eq (sb-kernel:fdefn-fun constant)
531                          function))
532             (funcall fn obj))))))))
533
534 ;;; XREF facility
535
536 (defun get-simple-fun (functoid)
537   (etypecase functoid
538     (sb-kernel::fdefn
539      (get-simple-fun (sb-vm::fdefn-fun functoid)))
540     ((or null sb-impl::funcallable-instance)
541      nil)
542     (function
543      (sb-kernel::%closure-fun functoid))))
544
545 (defun collect-xref (kind-index wanted-name)
546   (let ((ret nil))
547     (dolist (env sb-c::*info-environment* ret)
548       ;; Loop through the infodb ...
549       (sb-c::do-info (env :class class :type type :name info-name
550                           :value value)
551         ;; ... looking for function or macro definitions
552         (when (and (eql class :function)
553                    (or (eql type :macro-function)
554                        (eql type :definition)))
555           ;; Get a simple-fun for the definition, and an xref array
556           ;; from the table if available.
557           (let* ((simple-fun (get-simple-fun value))
558                  (xrefs (when simple-fun
559                           (sb-vm::%simple-fun-xrefs simple-fun)))
560                  (array (when xrefs
561                           (aref xrefs kind-index))))
562             ;; Loop through the name/path xref entries in the table
563             (loop for i from 0 below (length array) by 2
564                   for xref-name = (aref array i)
565                   for xref-path = (aref array (1+ i))
566                   do (when (eql xref-name wanted-name)
567                        (let ((source-location
568                               (find-function-definition-source simple-fun)))
569                          ;; Use the more accurate source path from
570                          ;; the xref entry.
571                          (setf (definition-source-form-path source-location)
572                                xref-path)
573                          (push (cons info-name source-location)
574                                ret))))))))))
575
576 (defun who-calls (function-name)
577   "Use the xref facility to search for source locations where the
578 global function named FUNCTION-NAME is called. Returns a list of
579 function name, definition-source pairs."
580   (collect-xref #.(position :calls sb-c::*xref-kinds*) function-name))
581
582 (defun who-binds (symbol)
583   "Use the xref facility to search for source locations where the
584 special variable SYMBOL is rebound. Returns a list of function name,
585 definition-source pairs."
586   (collect-xref #.(position :binds sb-c::*xref-kinds*) symbol))
587
588 (defun who-references (symbol)
589   "Use the xref facility to search for source locations where the
590 special variable or constant SYMBOL is read. Returns a list of function
591 name, definition-source pairs."
592   (collect-xref #.(position :references sb-c::*xref-kinds*) symbol))
593
594 (defun who-sets (symbol)
595   "Use the xref facility to search for source locations where the
596 special variable SYMBOL is written to. Returns a list of function name,
597 definition-source pairs."
598   (collect-xref #.(position :sets sb-c::*xref-kinds*) symbol))
599
600 (defun who-macroexpands (macro-name)
601   "Use the xref facility to search for source locations where the
602 macro MACRO-NAME is expanded. Returns a list of function name,
603 definition-source pairs."
604   (collect-xref #.(position :macroexpands sb-c::*xref-kinds*) macro-name))
605
606 (provide 'sb-introspect)