c48eb28b38357a639ef0a58a6ca825bb4c3d7eab
[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 ;;; 2) what should find-definition-source on a symbol return?  there may be
22 ;;;   several definitions (class, function, etc)
23 ;;; 3) error handling.  Signal random errors, or handle and resignal 'our'
24 ;;;   error, or return NIL?
25 ;;; 4) FIXMEs
26 ;;; 5) would be nice to have some interface to the compiler that lets us
27 ;;;   fake the filename and position, for use with C-M-x
28
29 (defpackage :sb-introspect
30   (:use "CL")
31   (:export "FUNCTION-ARGLIST"
32            "VALID-FUNCTION-NAME-P"
33            "FIND-DEFINITION-SOURCE"
34            "DEFINITION-SOURCE"
35            "DEFINITION-SOURCE-PATHNAME"
36            "DEFINITION-SOURCE-FORM-PATH"
37            "DEFINITION-SOURCE-CHARACTER-OFFSET"
38            "DEFINITION-SOURCE-FILE-WRITE-DATE"
39            "DEFINITION-SOURCE-PLIST"
40            "DEFINITION-NOT-FOUND" "DEFINITION-NAME"
41            "FIND-FUNCTION-CALLEES"
42            "FIND-FUNCTION-CALLERS"))
43
44 (in-package :sb-introspect)
45
46 ;;;; Internal interface for SBCL debug info
47
48 ;;; Here are some tutorial-style type definitions to help understand
49 ;;; the internal SBCL debugging data structures we're using. The
50 ;;; commentary is based on CMUCL's debug internals manual.
51 ;;;
52 (deftype debug-info ()
53   "Structure containing all the debug information related to a function.
54 Function objects reference debug-infos which in turn reference
55 debug-sources and so on."
56   'sb-c::compiled-debug-info)
57
58 (deftype debug-source ()
59   "Debug sources describe where to find source code.
60 For example, the debug source for a function compiled from a file will
61 include the pathname of the file and the position of the definition."
62   'sb-c::debug-source)
63
64 (deftype debug-function ()
65   "Debug function represent static compile-time information about a function."
66   'sb-c::compiled-debug-fun)
67
68 (declaim (ftype (function (function) debug-info) function-debug-info))
69 (defun function-debug-info (function)
70   (let* ((function-object (sb-kernel::%closure-fun function))
71          (function-header (sb-kernel:fun-code-header function-object)))
72     (sb-kernel:%code-debug-info function-header)))
73
74 (declaim (ftype (function (function) debug-source) function-debug-source))
75 (defun function-debug-source (function)
76   (debug-info-source (function-debug-info function)))
77
78 (declaim (ftype (function (debug-info) debug-source) debug-info-source))
79 (defun debug-info-source (debug-info)
80   (sb-c::debug-info-source debug-info))
81
82 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
83 (defun debug-info-debug-function (debug-info)
84   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
85
86 (defun valid-function-name-p (name)
87   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
88   (and (sb-int:valid-function-name-p name) t))
89
90 ;;;; Finding definitions
91
92 (defstruct definition-source
93   ;; Pathname of the source file that the definition was compiled from.
94   ;; This is null if the definition was not compiled from a file.
95   (pathname nil :type (or null pathname))
96   ;; Source-path of the definition within the file.
97   ;; This may be incomplete depending on the debug level at which the
98   ;; source was compiled.
99   (form-path '() :type list)
100   ;; Character offset of the top-level-form containing the definition.
101   ;; This corresponds to the first element of form-path.
102   (character-offset nil :type (or null integer))
103   ;; File-write-date of the source file when compiled.
104   ;; Null if not compiled from a file.
105   (file-write-date nil :type (or null integer))
106   ;; plist from WITH-COMPILATION-UNIT
107   (plist nil))
108
109 (defun find-definition-source (object)
110   (etypecase object
111     (method
112      (find-definition-source (or (sb-pcl::method-fast-function object)
113                                  (sb-pcl:method-function object))))
114     (function
115      (cond ((struct-accessor-p object)
116             (find-definition-source (struct-accessor-structure-class object)))
117            ((struct-predicate-p object)
118             (find-definition-source (struct-predicate-structure-class object)))
119            (t (find-function-definition-source object))))
120     (structure-class
121      (let ((constructor
122             (sb-kernel::structure-classoid-constructor
123              (sb-kernel:classoid-cell-classoid
124               (sb-int:info :type :classoid (class-name object))))))
125        (find-definition-source constructor)))
126     (t
127      (if (valid-function-name-p object)
128          (find-definition-source (or (macro-function object)
129                                      (fdefinition object)))))))
130
131 (defun find-function-definition-source (function)
132   (let* ((debug-info (function-debug-info function))
133          (debug-source (debug-info-source debug-info))
134          (debug-fun (debug-info-debug-function debug-info))
135          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
136     (make-definition-source
137      :pathname
138      (if (eql (sb-c::debug-source-from debug-source) :file)
139          (parse-namestring (sb-c::debug-source-name debug-source)))
140      :character-offset
141      (if tlf
142          (elt (sb-c::debug-source-start-positions debug-source) tlf))
143      ;; Unfortunately there is no proper source path available in the
144      ;; debug-source. FIXME: We could use sb-di:code-locations to get
145      ;; a full source path. -luke (12/Mar/2005)
146      :form-path (if tlf (list tlf))
147      :file-write-date (sb-c::debug-source-created debug-source)
148      :plist (sb-c::debug-source-plist debug-source))))
149
150 ;;; This is kludgey.  We expect these functions (the underlying functions,
151 ;;; not the closures) to be in static space and so not move ever.
152 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
153 ;;; accessors, e.g. when the :type option is used
154 (defvar *struct-slotplace-reader*
155   (sb-vm::%simple-fun-self #'definition-source-pathname))
156 (defvar *struct-slotplace-writer*
157   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
158 (defvar *struct-predicate*
159   (sb-vm::%simple-fun-self #'definition-source-p))
160
161 (defun struct-accessor-p (function)
162   (let ((self (sb-vm::%simple-fun-self function)))
163     ;; FIXME there are other kinds of struct accessor.  Fill out this list
164     (member self (list *struct-slotplace-reader*
165                        *struct-slotplace-writer*))))
166
167 (defun struct-predicate-p (function)
168   (let ((self (sb-vm::%simple-fun-self function)))
169     ;; FIXME there may be other structure predicate functions
170     (member self (list *struct-predicate*))))
171
172 ;;; FIXME: maybe this should be renamed as FUNCTION-LAMBDA-LIST?
173 (defun function-arglist (function)
174   "Describe the lambda list for the function designator FUNCTION.
175 Works for special-operators, macros, simple functions and generic
176 functions.  Signals error if not found"
177   (cond ((valid-function-name-p function)
178          (function-arglist
179           (or (macro-function function) (fdefinition function))))
180         ((typep function 'generic-function)
181          (sb-pcl::generic-function-pretty-arglist function))
182         (t (sb-impl::%simple-fun-arglist
183             (sb-impl::%closure-fun function)))))
184
185 (defun struct-accessor-structure-class (function)
186   (let ((self (sb-vm::%simple-fun-self function)))
187     (cond
188       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
189        (find-class
190         (sb-kernel::classoid-name
191          (sb-kernel::layout-classoid
192           (sb-kernel:%closure-index-ref function 1)))))
193       )))
194
195 (defun struct-predicate-structure-class (function)
196   (let ((self (sb-vm::%simple-fun-self function)))
197     (cond
198       ((member self (list *struct-predicate*))
199        (find-class
200         (sb-kernel::classoid-name
201          (sb-kernel::layout-classoid
202           (sb-kernel:%closure-index-ref function 0)))))
203       )))
204
205 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
206
207 ;;; This interface is trmendously experimental.
208
209 ;;; For the moment I'm taking the view that FDEFN is an internal
210 ;;; object (one out of one CMUCL developer surveyed didn't know what
211 ;;; they were for), so these routines deal in FUNCTIONs
212
213 ;;; Find callers and callees by looking at the constant pool of
214 ;;; compiled code objects.  We assume every fdefn object in the
215 ;;; constant pool corresponds to a call to that function.  A better
216 ;;; strategy would be to use the disassembler to find actual
217 ;;; call-sites.
218
219 (defun find-function-callees (function)
220   "Return functions called by FUNCTION."
221   (let ((callees '()))
222     (map-code-constants
223      (sb-kernel:fun-code-header function)
224      (lambda (obj)
225        (when (sb-kernel:fdefn-p obj)
226          (push (sb-kernel:fdefn-fun obj)
227                callees))))
228     callees))
229
230
231 (defun find-function-callers (function &optional (spaces '(:read-only :static
232                                                            :dynamic)))
233   "Return functions which call FUNCTION, by searching SPACES for code objects"
234   (let ((referrers '()))
235     (map-caller-code-components
236      function
237      spaces
238      (lambda (code)
239        (let ((entry (sb-kernel:%code-entry-points  code)))
240          (cond ((not entry)
241                 (push (princ-to-string code) referrers))
242                (t
243                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
244                       while e
245                       do (pushnew e referrers)))))))
246     referrers))
247
248 (declaim (inline map-code-constants))
249 (defun map-code-constants (code fn)
250   "Call FN for each constant in CODE's constant pool."
251   (check-type code sb-kernel:code-component)
252   (loop for i from sb-vm:code-constants-offset below
253         (sb-kernel:get-header-data code)
254         do (funcall fn (sb-kernel:code-header-ref code i))))
255
256 (declaim (inline map-allocated-code-components))
257 (defun map-allocated-code-components (spaces fn)
258   "Call FN for each allocated code component in one of SPACES.  FN
259 receives the object and its size as arguments.  SPACES should be a
260 list of the symbols :dynamic, :static, or :read-only."
261   (dolist (space spaces)
262     (sb-vm::map-allocated-objects
263      (lambda (obj header size)
264        (when (= sb-vm:code-header-widetag header)
265          (funcall fn obj size)))
266      space)))
267
268 (declaim (inline map-caller-code-components))
269 (defun map-caller-code-components (function spaces fn)
270   "Call FN for each code component with a fdefn for FUNCTION in its
271 constant pool."
272   (let ((function (coerce function 'function)))
273     (map-allocated-code-components
274      spaces
275      (lambda (obj size)
276        (declare (ignore size))
277        (map-code-constants
278         obj
279         (lambda (constant)
280           (when (and (sb-kernel:fdefn-p constant)
281                      (eq (sb-kernel:fdefn-fun constant)
282                          function))
283             (funcall fn obj))))))))
284
285 (provide 'sb-introspect)