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