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