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