1.0.35.12: Add SB-INTROSPECT:FUNCTION-TYPE.
[sbcl.git] / contrib / sb-introspect / introspect.lisp
1 ;;; introspection library
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 ;;; For the avoidance of doubt, the exported interface is the supported
13 ;;; interface. Anything else is internal, though you're welcome to argue a
14 ;;; case for exporting it.
15
16 ;;; If you steal the code from this file to cut and paste into your
17 ;;; own project, there will be much wailing and gnashing of teeth.
18 ;;; Your teeth.  If need be, we'll kick them for you.  This is a
19 ;;; contrib, we're allowed to look in internals.  You're an
20 ;;; application programmer, and are not.
21
22 ;;; TODO
23 ;;; 1) structs don't have within-file location info.  problem for the
24 ;;;   structure itself, accessors and the predicate
25 ;;; 3) error handling.  Signal random errors, or handle and resignal 'our'
26 ;;;   error, or return NIL?
27 ;;; 4) FIXMEs
28
29 (defpackage :sb-introspect
30   (:use "CL")
31   (:export "ALLOCATION-INFORMATION"
32            "FUNCTION-ARGLIST"
33            "FUNCTION-LAMBDA-LIST"
34            "FUNCTION-TYPE"
35            "DEFTYPE-LAMBDA-LIST"
36            "VALID-FUNCTION-NAME-P"
37            "FIND-DEFINITION-SOURCE"
38            "FIND-DEFINITION-SOURCES-BY-NAME"
39            "DEFINITION-SOURCE"
40            "DEFINITION-SOURCE-PATHNAME"
41            "DEFINITION-SOURCE-FORM-PATH"
42            "DEFINITION-SOURCE-CHARACTER-OFFSET"
43            "DEFINITION-SOURCE-FILE-WRITE-DATE"
44            "DEFINITION-SOURCE-PLIST"
45            "DEFINITION-NOT-FOUND" "DEFINITION-NAME"
46            "FIND-FUNCTION-CALLEES"
47            "FIND-FUNCTION-CALLERS"
48            "WHO-BINDS"
49            "WHO-CALLS"
50            "WHO-REFERENCES"
51            "WHO-SETS"
52            "WHO-MACROEXPANDS"
53            "WHO-SPECIALIZES-DIRECTLY"
54            "WHO-SPECIALIZES-GENERALLY"))
55
56 (in-package :sb-introspect)
57
58 ;;;; Internal interface for SBCL debug info
59
60 ;;; Here are some tutorial-style type definitions to help understand
61 ;;; the internal SBCL debugging data structures we're using. The
62 ;;; commentary is based on CMUCL's debug internals manual.
63 ;;;
64 (deftype debug-info ()
65   "Structure containing all the debug information related to a function.
66 Function objects reference debug-infos which in turn reference
67 debug-sources and so on."
68   'sb-c::compiled-debug-info)
69
70 (deftype debug-source ()
71   "Debug sources describe where to find source code.
72 For example, the debug source for a function compiled from a file will
73 include the pathname of the file and the position of the definition."
74   'sb-c::debug-source)
75
76 (deftype debug-function ()
77   "Debug function represent static compile-time information about a function."
78   'sb-c::compiled-debug-fun)
79
80 (declaim (ftype (function (function) debug-info) function-debug-info))
81 (defun function-debug-info (function)
82   (let* ((function-object (sb-kernel::%fun-fun function))
83          (function-header (sb-kernel:fun-code-header function-object)))
84     (sb-kernel:%code-debug-info function-header)))
85
86 (declaim (ftype (function (function) debug-source) function-debug-source))
87 (defun function-debug-source (function)
88   (debug-info-source (function-debug-info function)))
89
90 (declaim (ftype (function (debug-info) debug-source) debug-info-source))
91 (defun debug-info-source (debug-info)
92   (sb-c::debug-info-source debug-info))
93
94 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
95 (defun debug-info-debug-function (debug-info)
96   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
97
98 (defun valid-function-name-p (name)
99   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
100   (and (sb-int:valid-function-name-p name) t))
101
102 ;;;; Finding definitions
103
104 (defstruct definition-source
105   ;; Pathname of the source file that the definition was compiled from.
106   ;; This is null if the definition was not compiled from a file.
107   (pathname nil :type (or null pathname))
108   ;; Source-path of the definition within the file.
109   ;; This may be incomplete depending on the debug level at which the
110   ;; source was compiled.
111   (form-path '() :type list)
112   ;; Character offset of the top-level-form containing the definition.
113   ;; This corresponds to the first element of form-path.
114   (character-offset nil :type (or null integer))
115   ;; File-write-date of the source file when compiled.
116   ;; Null if not compiled from a file.
117   (file-write-date nil :type (or null integer))
118   ;; plist from WITH-COMPILATION-UNIT
119   (plist nil)
120   ;; Any extra metadata that the caller might be interested in. For
121   ;; example the specializers of the method whose definition-source this
122   ;; is.
123   (description nil :type list))
124
125 (defun find-definition-sources-by-name (name type)
126   "Returns a list of DEFINITION-SOURCEs for the objects of type TYPE
127 defined with name NAME. NAME may be a symbol or a extended function
128 name. Type can currently be one of the following:
129
130    (Public)
131    :CLASS
132    :COMPILER-MACRO
133    :CONDITION
134    :CONSTANT
135    :FUNCTION
136    :GENERIC-FUNCTION
137    :MACRO
138    :METHOD
139    :METHOD-COMBINATION
140    :PACKAGE
141    :SETF-EXPANDER
142    :STRUCTURE
143    :SYMBOL-MACRO
144    :TYPE
145    :VARIABLE
146
147    (Internal)
148    :OPTIMIZER
149    :SOURCE-TRANSFORM
150    :TRANSFORM
151    :VOP
152
153 If an unsupported TYPE is requested, the function will return NIL.
154 "
155   (flet ((listify (x)
156            (if (listp x)
157                x
158                (list x)))
159          (get-class (name)
160            (and (symbolp name)
161                 (find-class name nil)))
162          (real-fdefinition (name)
163            ;; for getting the real function object, even if the
164            ;; function is being profiled
165            (let ((profile-info (gethash name sb-profile::*profiled-fun-name->info*)))
166              (if profile-info
167                  (sb-profile::profile-info-encapsulated-fun profile-info)
168                  (fdefinition name)))))
169     (listify
170      (case type
171        ((:variable)
172         (when (and (symbolp name)
173                    (eq (sb-int:info :variable :kind name) :special))
174           (translate-source-location (sb-int:info :source-location type name))))
175        ((:constant)
176         (when (and (symbolp name)
177                    (eq (sb-int:info :variable :kind name) :constant))
178           (translate-source-location (sb-int:info :source-location type name))))
179        ((:symbol-macro)
180         (when (and (symbolp name)
181                    (eq (sb-int:info :variable :kind name) :macro))
182           (translate-source-location (sb-int:info :source-location type name))))
183        ((:macro)
184         (when (and (symbolp name)
185                    (macro-function name))
186           (find-definition-source (macro-function name))))
187        ((:compiler-macro)
188         (when (compiler-macro-function name)
189           (find-definition-source (compiler-macro-function name))))
190        ((:function :generic-function)
191         (when (and (fboundp name)
192                    (or (not (symbolp name))
193                        (not (macro-function name))))
194           (let ((fun (real-fdefinition name)))
195             (when (eq (not (typep fun 'generic-function))
196                       (not (eq type :generic-function)))
197               (find-definition-source fun)))))
198        ((:type)
199         ;; Source locations for types are saved separately when the expander
200         ;; is a closure without a good source-location.
201         (let ((loc (sb-int:info :type :source-location name)))
202           (if loc
203               (translate-source-location loc)
204               (let ((expander-fun (sb-int:info :type :expander name)))
205                 (when expander-fun
206                   (find-definition-source expander-fun))))))
207        ((:method)
208         (when (fboundp name)
209           (let ((fun (real-fdefinition name)))
210            (when (typep fun 'generic-function)
211              (loop for method in (sb-mop::generic-function-methods
212                                   fun)
213                 for source = (find-definition-source method)
214                 when source collect source)))))
215        ((:setf-expander)
216         (when (and (consp name)
217                    (eq (car name) 'setf))
218           (setf name (cadr name)))
219         (let ((expander (or (sb-int:info :setf :inverse name)
220                             (sb-int:info :setf :expander name))))
221           (when expander
222             (sb-introspect:find-definition-source (if (symbolp expander)
223                                                       (symbol-function expander)
224                                                       expander)))))
225        ((:structure)
226         (let ((class (get-class name)))
227           (if class
228               (when (typep class 'sb-pcl::structure-class)
229                 (find-definition-source class))
230               (when (sb-int:info :typed-structure :info name)
231                 (translate-source-location
232                  (sb-int:info :source-location :typed-structure name))))))
233        ((:condition :class)
234         (let ((class (get-class name)))
235           (when (and class
236                      (not (typep class 'sb-pcl::structure-class)))
237             (when (eq (not (typep class 'sb-pcl::condition-class))
238                       (not (eq type :condition)))
239               (find-definition-source class)))))
240        ((:method-combination)
241         (let ((combination-fun
242                (find-method #'sb-mop:find-method-combination
243                             nil
244                             (list (find-class 'generic-function)
245                                   (list 'eql name)
246                                   t)
247                             nil)))
248           (when combination-fun
249             (find-definition-source combination-fun))))
250        ((:package)
251         (when (symbolp name)
252           (let ((package (find-package name)))
253             (when package
254               (find-definition-source package)))))
255        ;; TRANSFORM and OPTIMIZER handling from swank-sbcl
256        ((:transform)
257         (when (symbolp name)
258           (let ((fun-info (sb-int:info :function :info name)))
259             (when fun-info
260               (loop for xform in (sb-c::fun-info-transforms fun-info)
261                     for source = (find-definition-source
262                                   (sb-c::transform-function xform))
263                     for typespec = (sb-kernel:type-specifier
264                                     (sb-c::transform-type xform))
265                     for note = (sb-c::transform-note xform)
266                     do (setf (definition-source-description source)
267                              (if (consp typespec)
268                                  (list (second typespec) note)
269                                  (list note)))
270                     collect source)))))
271        ((:optimizer)
272         (when (symbolp name)
273           (let ((fun-info (sb-int:info :function :info name)))
274             (when fun-info
275               (let ((otypes '((sb-c::fun-info-derive-type . sb-c:derive-type)
276                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
277                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
278                               (sb-c::fun-info-optimizer . sb-c:optimizer))))
279                 (loop for (reader . name) in otypes
280                       for fn = (funcall reader fun-info)
281                       when fn collect
282                       (let ((source (find-definition-source fn)))
283                         (setf (definition-source-description source)
284                               (list name))
285                         source)))))))
286        ((:vop)
287         (when (symbolp name)
288           (let ((fun-info (sb-int:info :function :info name)))
289             (when fun-info
290               (loop for vop in (sb-c::fun-info-templates fun-info)
291                     for source = (find-definition-source
292                                   (sb-c::vop-info-generator-function vop))
293                     do (setf (definition-source-description source)
294                              (list (sb-c::template-name vop)
295                                    (sb-c::template-note vop)))
296                     collect source)))))
297        ((:source-transform)
298         (when (symbolp name)
299           (let ((transform-fun (sb-int:info :function :source-transform name)))
300             (when transform-fun
301               (sb-introspect:find-definition-source transform-fun)))))
302        (t
303         nil)))))
304
305 (defun find-definition-source (object)
306   (typecase object
307     ((or sb-pcl::condition-class sb-pcl::structure-class)
308      (let ((classoid (sb-impl::find-classoid (class-name object))))
309        (when classoid
310          (let ((layout (sb-impl::classoid-layout classoid)))
311            (when layout
312              (translate-source-location
313               (sb-kernel::layout-source-location layout)))))))
314     (method-combination
315      (car
316       (find-definition-sources-by-name
317        (sb-pcl::method-combination-type-name object) :method-combination)))
318     (package
319      (translate-source-location (sb-impl::package-source-location object)))
320     (class
321      (translate-source-location (sb-pcl::definition-source object)))
322     ;; Use the PCL definition location information instead of the function
323     ;; debug-info for methods and generic functions. Sometimes the
324     ;; debug-info would point into PCL internals instead of the proper
325     ;; location.
326     (generic-function
327      (let ((source (translate-source-location
328                     (sb-pcl::definition-source object))))
329        (when source
330          (setf (definition-source-description source)
331                (list (sb-mop:generic-function-lambda-list object))))
332        source))
333     (method
334      (let ((source (translate-source-location
335                     (sb-pcl::definition-source object))))
336        (when source
337          (setf (definition-source-description source)
338                (append (method-qualifiers object)
339                        (if (sb-mop:method-generic-function object)
340                            (sb-pcl::unparse-specializers
341                             (sb-mop:method-generic-function object)
342                             (sb-mop:method-specializers object))
343                            (sb-mop:method-specializers object)))))
344        source))
345     #+sb-eval
346     (sb-eval:interpreted-function
347      (let ((source (translate-source-location
348                     (sb-eval:interpreted-function-source-location object))))
349        source))
350     (function
351      (cond ((struct-accessor-p object)
352             (find-definition-source
353              (struct-accessor-structure-class object)))
354            ((struct-predicate-p object)
355             (find-definition-source
356              (struct-predicate-structure-class object)))
357            (t
358             (find-function-definition-source object))))
359     ((or condition standard-object structure-object)
360      (find-definition-source (class-of object)))
361     (t
362      (error "Don't know how to retrieve source location for a ~S"
363             (type-of object)))))
364
365 (defun find-function-definition-source (function)
366   (let* ((debug-info (function-debug-info function))
367          (debug-source (debug-info-source debug-info))
368          (debug-fun (debug-info-debug-function debug-info))
369          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
370     (make-definition-source
371      :pathname
372      ;; KLUDGE: at the moment, we don't record the correct toplevel
373      ;; form number for forms processed by EVAL (including EVAL-WHEN
374      ;; :COMPILE-TOPLEVEL).  Until that's fixed, don't return a
375      ;; DEFINITION-SOURCE with a pathname.  (When that's fixed, take
376      ;; out the (not (debug-source-form ...)) test.
377      (if (and (sb-c::debug-source-namestring debug-source)
378               (not (sb-c::debug-source-form debug-source)))
379          (parse-namestring (sb-c::debug-source-namestring debug-source)))
380      :character-offset
381      (if tlf
382          (elt (sb-c::debug-source-start-positions debug-source) tlf))
383      ;; Unfortunately there is no proper source path available in the
384      ;; debug-source. FIXME: We could use sb-di:code-locations to get
385      ;; a full source path. -luke (12/Mar/2005)
386      :form-path (if tlf (list tlf))
387      :file-write-date (sb-c::debug-source-created debug-source)
388      :plist (sb-c::debug-source-plist debug-source))))
389
390 (defun translate-source-location (location)
391   (if location
392       (make-definition-source
393        :pathname (let ((n (sb-c:definition-source-location-namestring location)))
394                    (when n
395                      (parse-namestring n)))
396        :form-path
397        (let ((number (sb-c:definition-source-location-toplevel-form-number
398                          location)))
399          (when number
400            (list number)))
401        :plist (sb-c:definition-source-location-plist location))
402       (make-definition-source)))
403
404 ;;; This is kludgey.  We expect these functions (the underlying functions,
405 ;;; not the closures) to be in static space and so not move ever.
406 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
407 ;;; accessors, e.g. when the :type option is used
408 (defvar *struct-slotplace-reader*
409   (sb-vm::%simple-fun-self #'definition-source-pathname))
410 (defvar *struct-slotplace-writer*
411   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
412 (defvar *struct-predicate*
413   (sb-vm::%simple-fun-self #'definition-source-p))
414
415 (defun struct-accessor-p (function)
416   (let ((self (sb-vm::%simple-fun-self function)))
417     ;; FIXME there are other kinds of struct accessor.  Fill out this list
418     (member self (list *struct-slotplace-reader*
419                        *struct-slotplace-writer*))))
420
421 (defun struct-predicate-p (function)
422   (let ((self (sb-vm::%simple-fun-self function)))
423     ;; FIXME there may be other structure predicate functions
424     (member self (list *struct-predicate*))))
425
426 (defun function-arglist (function)
427   "Deprecated alias for FUNCTION-LAMBDA-LIST."
428   (function-lambda-list function))
429
430 (define-compiler-macro function-arglist (function)
431   (sb-int:deprecation-warning 'function-arglist 'function-lambda-list)
432   `(function-lambda-list ,function))
433
434 (defun function-lambda-list (function)
435   "Describe the lambda list for the extended function designator FUNCTION.
436 Works for special-operators, macros, simple functions, interpreted functions,
437 and generic functions. Signals an error if FUNCTION is not a valid extended
438 function designator."
439   (cond ((valid-function-name-p function)
440          (function-lambda-list (or (and (symbolp function)
441                                         (macro-function function))
442                                    (fdefinition function))))
443         ((typep function 'generic-function)
444          (sb-pcl::generic-function-pretty-arglist function))
445         #+sb-eval
446         ((typep function 'sb-eval:interpreted-function)
447          (sb-eval:interpreted-function-lambda-list function))
448         (t
449          (sb-kernel:%simple-fun-arglist (sb-kernel:%fun-fun function)))))
450
451 (defun deftype-lambda-list (typespec-operator)
452   "Returns the lambda list of TYPESPEC-OPERATOR as first return
453 value, and a flag whether the arglist could be found as second
454 value."
455   (check-type typespec-operator symbol)
456   (case (sb-int:info :type :kind typespec-operator)
457     (:defined
458      (sb-int:info :type :lambda-list typespec-operator))
459     (:primitive
460      (let ((translator-fun (sb-int:info :type :translator typespec-operator)))
461        (if translator-fun
462            (values (sb-kernel:%fun-lambda-list translator-fun) t)
463            ;; Some builtin types (e.g. STRING) do not have a
464            ;; translator, but they were actually defined via DEFTYPE
465            ;; in src/code/deftypes-for-target.lisp.
466            (sb-int:info :type :lambda-list typespec-operator))))
467     (t (values nil nil))))
468
469 (defun function-type (function-designator)
470   "Returns the ftype of FUNCTION-DESIGNATOR, or NIL."
471   (flet ((ftype-of (function-designator)
472            (sb-kernel:type-specifier
473             (sb-int:info :function :type function-designator))))
474     (etypecase function-designator
475       (symbol
476        (when (and (fboundp function-designator)
477                   (not (macro-function function-designator))
478                   (not (special-operator-p function-designator)))
479          (ftype-of function-designator)))
480       (cons
481        (when (and (sb-int:legal-fun-name-p function-designator)
482                   (fboundp function-designator))
483          (ftype-of function-designator)))
484       (generic-function
485        (function-type (sb-pcl:generic-function-name function-designator)))
486       (function
487        ;; Give declared type in globaldb priority over derived type
488        ;; because it contains more accurate information e.g. for
489        ;; struct-accessors.
490        (let ((type (function-type (sb-kernel:%fun-name
491                                    (sb-impl::%fun-fun function-designator)))))
492          (if type
493              type
494              (sb-impl::%fun-type function-designator)))))))
495
496 (defun struct-accessor-structure-class (function)
497   (let ((self (sb-vm::%simple-fun-self function)))
498     (cond
499       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
500        (find-class
501         (sb-kernel::classoid-name
502          (sb-kernel::layout-classoid
503           (sb-kernel:%closure-index-ref function 1)))))
504       )))
505
506 (defun struct-predicate-structure-class (function)
507   (let ((self (sb-vm::%simple-fun-self function)))
508     (cond
509       ((member self (list *struct-predicate*))
510        (find-class
511         (sb-kernel::classoid-name
512          (sb-kernel::layout-classoid
513           (sb-kernel:%closure-index-ref function 0)))))
514       )))
515
516 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
517
518 ;;; This interface is trmendously experimental.
519
520 ;;; For the moment I'm taking the view that FDEFN is an internal
521 ;;; object (one out of one CMUCL developer surveyed didn't know what
522 ;;; they were for), so these routines deal in FUNCTIONs
523
524 ;;; Find callers and callees by looking at the constant pool of
525 ;;; compiled code objects.  We assume every fdefn object in the
526 ;;; constant pool corresponds to a call to that function.  A better
527 ;;; strategy would be to use the disassembler to find actual
528 ;;; call-sites.
529
530 (defun find-function-callees (function)
531   "Return functions called by FUNCTION."
532   (let ((callees '()))
533     (map-code-constants
534      (sb-kernel:fun-code-header function)
535      (lambda (obj)
536        (when (sb-kernel:fdefn-p obj)
537          (push (sb-kernel:fdefn-fun obj)
538                callees))))
539     callees))
540
541
542 (defun find-function-callers (function &optional (spaces '(:read-only :static
543                                                            :dynamic)))
544   "Return functions which call FUNCTION, by searching SPACES for code objects"
545   (let ((referrers '()))
546     (map-caller-code-components
547      function
548      spaces
549      (lambda (code)
550        (let ((entry (sb-kernel:%code-entry-points  code)))
551          (cond ((not entry)
552                 (push (princ-to-string code) referrers))
553                (t
554                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
555                       while e
556                       do (pushnew e referrers)))))))
557     referrers))
558
559 (declaim (inline map-code-constants))
560 (defun map-code-constants (code fn)
561   "Call FN for each constant in CODE's constant pool."
562   (check-type code sb-kernel:code-component)
563   (loop for i from sb-vm:code-constants-offset below
564         (sb-kernel:get-header-data code)
565         do (funcall fn (sb-kernel:code-header-ref code i))))
566
567 (declaim (inline map-allocated-code-components))
568 (defun map-allocated-code-components (spaces fn)
569   "Call FN for each allocated code component in one of SPACES.  FN
570 receives the object and its size as arguments.  SPACES should be a
571 list of the symbols :dynamic, :static, or :read-only."
572   (dolist (space spaces)
573     (sb-vm::map-allocated-objects
574      (lambda (obj header size)
575        (when (= sb-vm:code-header-widetag header)
576          (funcall fn obj size)))
577      space
578      t)))
579
580 (declaim (inline map-caller-code-components))
581 (defun map-caller-code-components (function spaces fn)
582   "Call FN for each code component with a fdefn for FUNCTION in its
583 constant pool."
584   (let ((function (coerce function 'function)))
585     (map-allocated-code-components
586      spaces
587      (lambda (obj size)
588        (declare (ignore size))
589        (map-code-constants
590         obj
591         (lambda (constant)
592           (when (and (sb-kernel:fdefn-p constant)
593                      (eq (sb-kernel:fdefn-fun constant)
594                          function))
595             (funcall fn obj))))))))
596
597 ;;; XREF facility
598
599 (defun get-simple-fun (functoid)
600   (etypecase functoid
601     (sb-kernel::fdefn
602      (get-simple-fun (sb-vm::fdefn-fun functoid)))
603     ((or null sb-impl::funcallable-instance)
604      nil)
605     (function
606      (sb-kernel::%fun-fun functoid))))
607
608 (defun collect-xref (kind-index wanted-name)
609   (let ((ret nil))
610     (dolist (env sb-c::*info-environment* ret)
611       ;; Loop through the infodb ...
612       (sb-c::do-info (env :class class :type type :name info-name
613                           :value value)
614         ;; ... looking for function or macro definitions
615         (when (and (eql class :function)
616                    (or (eql type :macro-function)
617                        (eql type :definition)))
618           ;; Get a simple-fun for the definition, and an xref array
619           ;; from the table if available.
620           (let* ((simple-fun (get-simple-fun value))
621                  (xrefs (when simple-fun
622                           (sb-kernel:%simple-fun-xrefs simple-fun)))
623                  (array (when xrefs
624                           (aref xrefs kind-index))))
625             ;; Loop through the name/path xref entries in the table
626             (loop for i from 0 below (length array) by 2
627                   for xref-name = (aref array i)
628                   for xref-path = (aref array (1+ i))
629                   do (when (eql xref-name wanted-name)
630                        (let ((source-location
631                               (find-function-definition-source simple-fun)))
632                          ;; Use the more accurate source path from
633                          ;; the xref entry.
634                          (setf (definition-source-form-path source-location)
635                                xref-path)
636                          (push (cons info-name source-location)
637                                ret))))))))))
638
639 (defun who-calls (function-name)
640   "Use the xref facility to search for source locations where the
641 global function named FUNCTION-NAME is called. Returns a list of
642 function name, definition-source pairs."
643   (collect-xref #.(position :calls sb-c::*xref-kinds*) function-name))
644
645 (defun who-binds (symbol)
646   "Use the xref facility to search for source locations where the
647 special variable SYMBOL is rebound. Returns a list of function name,
648 definition-source pairs."
649   (collect-xref #.(position :binds sb-c::*xref-kinds*) symbol))
650
651 (defun who-references (symbol)
652   "Use the xref facility to search for source locations where the
653 special variable or constant SYMBOL is read. Returns a list of function
654 name, definition-source pairs."
655   (collect-xref #.(position :references sb-c::*xref-kinds*) symbol))
656
657 (defun who-sets (symbol)
658   "Use the xref facility to search for source locations where the
659 special variable SYMBOL is written to. Returns a list of function name,
660 definition-source pairs."
661   (collect-xref #.(position :sets sb-c::*xref-kinds*) symbol))
662
663 (defun who-macroexpands (macro-name)
664   "Use the xref facility to search for source locations where the
665 macro MACRO-NAME is expanded. Returns a list of function name,
666 definition-source pairs."
667   (collect-xref #.(position :macroexpands sb-c::*xref-kinds*) macro-name))
668
669 (defun who-specializes-directly (class-designator)
670   "Search for source locations of methods directly specializing on
671 CLASS-DESIGNATOR. Returns an alist of method name, definition-source
672 pairs.
673
674 A method matches the criterion either if it specializes on the same
675 class as CLASS-DESIGNATOR designates (this includes CLASS-EQ
676 specializers), or if it eql-specializes on an instance of the
677 designated class.
678
679 Experimental.
680 "
681   (let ((class (canonicalize-class-designator class-designator)))
682     (unless class
683       (return-from who-specializes-directly nil))
684     (let ((result (collect-specializing-methods
685                    #'(lambda (specl)
686                        ;; Does SPECL specialize on CLASS directly?
687                        (typecase specl
688                          (sb-pcl::class-eq-specializer
689                           (eq (sb-pcl::specializer-object specl) class))
690                          (sb-pcl::eql-specializer
691                           (let ((obj (sb-mop:eql-specializer-object specl)))
692                             (eq (class-of obj) class)))
693                          ((not sb-pcl::standard-specializer)
694                           nil)
695                          (t
696                           (eq specl class)))))))
697       (map-into result #'(lambda (m)
698                            (cons `(method ,(method-generic-function-name m))
699                                  (find-definition-source m)))
700                 result))))
701
702 (defun who-specializes-generally (class-designator)
703   "Search for source locations of methods specializing on
704 CLASS-DESIGNATOR, or a subclass of it. Returns an alist of method
705 name, definition-source pairs.
706
707 A method matches the criterion either if it specializes on the
708 designated class itself or a subclass of it (this includes CLASS-EQ
709 specializers), or if it eql-specializes on an instance of the
710 designated class or a subclass of it.
711
712 Experimental.
713 "
714   (let ((class (canonicalize-class-designator class-designator)))
715     (unless class
716       (return-from who-specializes-generally nil))
717     (let ((result (collect-specializing-methods
718                    #'(lambda (specl)
719                        ;; Does SPECL specialize on CLASS or a subclass
720                        ;; of it?
721                        (typecase specl
722                          (sb-pcl::class-eq-specializer
723                           (subtypep (sb-pcl::specializer-object specl) class))
724                          (sb-pcl::eql-specializer
725                           (typep (sb-mop:eql-specializer-object specl) class))
726                          ((not sb-pcl::standard-specializer)
727                           nil)
728                          (t
729                           (subtypep specl class)))))))
730       (map-into result #'(lambda (m)
731                            (cons `(method ,(method-generic-function-name m))
732                                  (find-definition-source m)))
733                 result))))
734
735 (defun canonicalize-class-designator (class-designator)
736   (typecase class-designator
737     (symbol (find-class class-designator nil))
738     (class  class-designator)
739     (t nil)))
740
741 (defun method-generic-function-name (method)
742   (sb-mop:generic-function-name (sb-mop:method-generic-function method)))
743
744 (defun collect-specializing-methods (predicate)
745   (let ((result '()))
746     (sb-pcl::map-specializers
747      #'(lambda (specl)
748          (when (funcall predicate specl)
749            (let ((methods (sb-mop:specializer-direct-methods specl)))
750              (setf result (append methods result))))))
751     (delete-duplicates result)))
752
753
754 ;;;; ALLOCATION INTROSPECTION
755
756 (defun allocation-information (object)
757   #+sb-doc
758   "Returns information about the allocation of OBJECT. Primary return value
759 indicates the general type of allocation: :IMMEDIATE, :HEAP, :STACK,
760 or :FOREIGN.
761
762 Possible secondary return value provides additional information about the
763 allocation.
764
765 For :HEAP objects the secondary value is a plist:
766
767   :SPACE
768     Inficates the heap segment the object is allocated in.
769
770   :GENERATION
771     Is the current generation of the object: 0 for nursery, 6 for pseudo-static
772     generation loaded from core. (GENCGC and :SPACE :DYNAMIC only.)
773
774   :LARGE
775     Indicates a \"large\" object subject to non-copying
776     promotion. (GENCGC and :SPACE :DYNAMIC only.)
777
778   :BOXED
779     Indicates that the object is allocated in a boxed region. Unboxed
780     allocation is used for eg. specialized arrays after they have survived one
781     collection. (GENCGC and :SPACE :DYNAMIC only.)
782
783   :PINNED
784     Indicates that the page(s) on which the object resides are kept live due
785     to conservative references. Note that object may reside on a pinned page
786     even if :PINNED in NIL if the GC has not had the need to mark the the page
787     as pinned. (GENCGC and :SPACE :DYNAMIC only.)
788
789 For :STACK objects secondary value is the thread on whose stack the object is
790 allocated.
791
792 Expected use-cases include introspection to gain insight into allocation and
793 GC behaviour and restricting memoization to heap-allocated arguments.
794
795 Experimental: interface subject to change."
796   ;; FIXME: Would be nice to provide the size of the object as well, though
797   ;; maybe that should be a separate function, and something like MAP-PARTS
798   ;; for mapping over parts of arbitrary objects so users can get "deep sizes"
799   ;; as well if they want to.
800   ;;
801   ;; FIXME: For the memoization use-case possibly we should also provide a
802   ;; simpler HEAP-ALLOCATED-P, since that doesn't require disabling the GC
803   ;; scanning threads for negative answers? Similarly, STACK-ALLOCATED-P for
804   ;; checking if an object has been stack-allocated by a given thread for
805   ;; testing purposes might not come amiss.
806   (if (typep object '(or fixnum character))
807       (values :immediate nil)
808       (let ((plist
809              (sb-sys:without-gcing
810                ;; Disable GC so the object cannot move to another page while
811                ;; we have the address.
812                (let* ((addr (sb-kernel:get-lisp-obj-address object))
813                       (space
814                        (cond ((< sb-vm:read-only-space-start addr
815                                  (* sb-vm:*read-only-space-free-pointer*
816                                     sb-vm:n-word-bytes))
817                               :read-only)
818                              ((< sb-vm:static-space-start addr
819                                  (* sb-vm:*static-space-free-pointer*
820                                     sb-vm:n-word-bytes))
821                               :static)
822                              ((< (sb-kernel:current-dynamic-space-start) addr
823                                  (sb-sys:sap-int (sb-kernel:dynamic-space-free-pointer)))
824                               :dynamic))))
825                  (when space
826                    #+gencgc
827                    (if (eq :dynamic space)
828                        (let ((index (sb-vm::find-page-index addr)))
829                          (symbol-macrolet ((page (sb-alien:deref sb-vm::page-table index)))
830                            (let ((flags (sb-alien:slot page 'sb-vm::flags)))
831                              (list :space space
832                                    :generation (sb-alien:slot page 'sb-vm::gen)
833                                    :write-protected (logbitp 0 flags)
834                                    :boxed (logbitp 2 flags)
835                                    :pinned (logbitp 5 flags)
836                                    :large (logbitp 6 flags)))))
837                        (list :space space))
838                    #-gencgc
839                    (list :space space))))))
840         (cond (plist
841                (values :heap plist))
842               (t
843                (let ((sap (sb-sys:int-sap (sb-kernel:get-lisp-obj-address object))))
844                  ;; FIXME: Check other stacks as well.
845                  #+sb-thread
846                  (dolist (thread (sb-thread:list-all-threads))
847                    (let ((c-start (sb-di::descriptor-sap
848                                    (sb-thread::%symbol-value-in-thread
849                                     'sb-vm:*control-stack-start*
850                                     thread)))
851                          (c-end (sb-di::descriptor-sap
852                                  (sb-thread::%symbol-value-in-thread
853                                   'sb-vm:*control-stack-end*
854                                   thread))))
855                      (when (and c-start c-end)
856                        (when (and (sb-sys:sap<= c-start sap)
857                                   (sb-sys:sap< sap c-end))
858                          (return-from allocation-information
859                            (values :stack thread))))))
860                  #-sb-thread
861                  (when (sb-vm:control-stack-pointer-valid-p sap nil)
862                    (return-from allocation-information
863                      (values :stack sb-thread::*current-thread*))))
864                :foreign)))))
865