ViewVC logotype

Diff of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.32 by heller, Wed Dec 3 22:34:50 2003 UTC revision 1.99 by lgorrie, Sun May 2 02:19:35 2004 UTC
# Line 1  Line 1 
1  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
3  (declaim (optimize debug))  (declaim (optimize (debug 2)))
5  (in-package :swank)  (in-package :swank-backend)
7  ;; Turn on xref. [should we?]  (in-package :lisp)
 (setf c:*record-xref-info* t)  
9  (defun without-interrupts* (body)  ;; Fix for read-sequence in 18e
10    (sys:without-interrupts (funcall body)))  #+cmu18e
11    (progn
12      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
13        (when s
14          (setf (symbol-value s) nil)))
16      (defun read-into-simple-string (s stream start end)
17        (declare (type simple-string s))
18        (declare (type stream stream))
19        (declare (type index start end))
20        (unless (subtypep (stream-element-type stream) 'character)
21          (error 'type-error
22                 :datum (read-char stream nil #\Null)
23                 :expected-type (stream-element-type stream)
24                 :format-control "Trying to read characters from a binary stream."))
25        ;; Let's go as low level as it seems reasonable.
26        (let* ((numbytes (- end start))
27               (total-bytes 0))
28          ;; read-n-bytes may return fewer bytes than requested, so we need
29          ;; to keep trying.
30          (loop while (plusp numbytes) do
31                (let ((bytes-read (system:read-n-bytes stream s start numbytes nil)))
32                  (when (zerop bytes-read)
33                    (return-from read-into-simple-string total-bytes))
34                  (incf total-bytes bytes-read)
35                  (incf start bytes-read)
36                  (decf numbytes bytes-read)))
37          total-bytes))
39      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
40        (when s
41          (setf (symbol-value s) t)))
43  (defun set-fd-non-blocking (fd)    )
44    (flet ((fcntl (fd cmd arg)  
45             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)  (in-package :swank-backend)
              (or flags  
                  (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))  
     (let ((flags (fcntl fd unix:F-GETFL 0)))  
       (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))  
48  ;;;; TCP server.  ;;;; TCP server.
50  (defun resolve-hostname (name)  (defimplementation preferred-communication-style ()
51    (let* ((hostent (ext:lookup-host-entry name))    :sigio)
53    (defimplementation create-socket (host port)
54      (ext:create-inet-listener port :stream
55                                :reuse-address t
56                                :host (resolve-hostname host)))
58    (defimplementation local-port (socket)
59      (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
61    (defimplementation close-socket (socket)
62      (ext:close-socket (socket-fd socket)))
64    (defimplementation accept-connection (socket)
65      #+mp (mp:process-wait-until-fd-usable socket :input)
66      (make-socket-io-stream (ext:accept-tcp-connection socket)))
68    (defvar *sigio-handlers* '()
69      "List of (key . (fn . args)) pairs to be called on SIGIO.")
71    (defun sigio-handler (signal code scp)
72      (declare (ignore signal code scp))
73      (mapc (lambda (handler) (funcall (cdr handler))) *sigio-handlers*))
75    (defun set-sigio-handler ()
76      (sys:enable-interrupt unix:sigio (lambda (signal code scp)
77                                         (sigio-handler signal code scp))))
79    (defun fcntl (fd command arg)
80      (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
81        (cond (ok)
82              (t (error "fcntl: ~A" (unix:get-unix-error-msg error))))))
84    (defimplementation add-sigio-handler (socket fn)
85      (set-sigio-handler)
86      (let ((fd (socket-fd socket)))
87        (format *debug-io* "; Adding input handler: ~S ~%" fd)
88        (fcntl fd unix:f-setown (unix:unix-getpid))
89        (fcntl fd unix:f-setfl unix:fasync)
90        (push (cons fd fn) *sigio-handlers*)))
92    (defimplementation remove-sigio-handlers (socket)
93      (let ((fd (socket-fd socket)))
94        (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car))
95        (sys:invalidate-descriptor fd))
96      (close socket))
98    (defimplementation add-fd-handler (socket fn)
99      (let ((fd (socket-fd socket)))
100        (format *debug-io* "; Adding fd handler: ~S ~%" fd)
101        (sys:add-fd-handler fd :input (lambda (_)
102                                        _
103                                        (funcall fn)))))
105    (defimplementation remove-fd-handlers (socket)
106      (sys:invalidate-descriptor (socket-fd socket)))
108    (defimplementation make-fn-streams (input-fn output-fn)
109      (let* ((output (make-slime-output-stream output-fn))
110             (input  (make-slime-input-stream input-fn output)))
111        (values input output)))
113    ;;;;; Socket helpers.
115    (defun socket-fd (socket)
116      "Return the filedescriptor for the socket represented by SOCKET."
117      (etypecase socket
118        (fixnum socket)
119        (sys:fd-stream (sys:fd-stream-fd socket))))
121    (defun resolve-hostname (hostname)
122      "Return the IP address of HOSTNAME as an integer."
123      (let* ((hostent (ext:lookup-host-entry hostname))
124           (address (car (ext:host-entry-addr-list hostent))))           (address (car (ext:host-entry-addr-list hostent))))
125      (ext:htonl address)))      (ext:htonl address)))
127  (defun create-swank-server (port &key (reuse-address t)  (defun make-socket-io-stream (fd)
128                              (address "localhost"))    "Create a new input/output fd-stream for FD."
129    "Create a SWANK TCP server."    (sys:make-fd-stream fd :input t :output t :element-type 'base-char))
130    (let* ((ip (resolve-hostname address))  
131           (fd (ext:create-inet-listener port :stream  (defun set-fd-non-blocking (fd)
132                                         :reuse-address reuse-address    (flet ((fcntl (fd cmd arg)
133                                         :host ip)))             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)
134      (system:add-fd-handler fd :input #'accept-connection)               (or flags
135      (nth-value 1 (ext::get-socket-host-and-port fd))))                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))
136        (let ((flags (fcntl fd unix:f-getfl 0)))
137  (defun accept-connection (socket)        (fcntl fd unix:f-setfl (logior flags unix:o_nonblock)))))
138    "Accept one Swank TCP connection on SOCKET and then close it."  
139    (setup-request-handler (ext:accept-tcp-connection socket))  
140    (sys:invalidate-descriptor socket)  ;;;; unix signals
141    (unix:unix-close socket))  
142    (defmethod call-without-interrupts (fn)
143  (defun open-stream-to-emacs ()    (sys:without-interrupts (funcall fn)))
144    "Return an output-stream to Emacs' output buffer."  
145    (let* ((ip (resolve-hostname "localhost"))  (defimplementation getpid ()
146           (listener (ext:create-inet-listener 0 :stream :host ip))    (unix:unix-getpid))
147           (port (nth-value 1 (ext::get-socket-host-and-port listener))))  
148      (unwind-protect  (defimplementation lisp-implementation-type-name ()
149           (progn    "cmucl")
            (eval-in-emacs `(slime-open-stream-to-lisp ,port))  
            (let ((fd (ext:accept-tcp-connection listener)))  
              (sys:make-fd-stream fd :output t)))  
       (ext:close-socket listener))))  
 (defvar *use-dedicated-output-stream* t)  
 (defun setup-request-handler (socket)  
   "Setup request handling for SOCKET."  
   (let* ((stream (sys:make-fd-stream socket  
                                      :input t :output t  
                                      :element-type 'base-char))  
          (input (make-slime-input-stream))  
          (output (if *use-dedicated-output-stream*  
                      (let ((*emacs-io* stream)) (open-stream-to-emacs))  
          (io (make-two-way-stream input output)))  
     (system:add-fd-handler socket  
                            :input (lambda (fd)  
                                     (declare (ignore fd))  
                                     (serve-request stream output input io)))))  
 (defun serve-request (*emacs-io* *slime-output* *slime-input* *slime-io*)  
   "Read and process a request from a SWANK client.  
 The request is read from the socket as a sexp and then evaluated."  
   (catch 'slime-toplevel  
     (with-simple-restart (abort "Return to Slime toplevel.")  
       (handler-case (read-from-emacs)  
         (slime-read-error (e)  
           (when *swank-debug-p*  
             (format *debug-io* "~&;; Connection to Emacs lost.~%;; [~A]~%" e))  
           (sys:invalidate-descriptor (sys:fd-stream-fd *emacs-io*))  
           (close *emacs-io*)))))  
152  ;;;; Stream handling  ;;;; Stream handling
154  (defstruct (slime-output-stream  (defstruct (slime-output-stream
155               (:include lisp::lisp-stream               (:include lisp::lisp-stream
156                         (lisp::misc #'sos/misc)                         (lisp::misc #'sos/misc)
157                         (lisp::out #'sos/out)                         (lisp::out #'sos/out)
158                         (lisp::sout #'sos/sout))                         (lisp::sout #'sos/sout))
159               (:conc-name sos.)               (:conc-name sos.)
160               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
161                 (:constructor make-slime-output-stream (output-fn)))
162      (output-fn nil :type function)
163    (buffer (make-string 512) :type string)    (buffer (make-string 512) :type string)
164    (index 0 :type kernel:index)    (index 0 :type kernel:index)
165    (column 0 :type kernel:index))    (column 0 :type kernel:index))
# Line 117  The request is read from the socket as a Line 183  The request is read from the socket as a
183  (defun sos/sout (stream string start end)  (defun sos/sout (stream string start end)
184    (loop for i from start below end    (loop for i from start below end
185          do (sos/out stream (aref string i))))          do (sos/out stream (aref string i))))
187  (defun sos/misc (stream operation &optional arg1 arg2)  (defun sos/misc (stream operation &optional arg1 arg2)
188    (declare (ignore arg1 arg2))    (declare (ignore arg1 arg2))
189    (case operation    (case operation
190      ((:force-output :finish-output)      ((:force-output :finish-output)
191       (let ((end (sos.index stream)))       (let ((end (sos.index stream)))
192         (unless (zerop end)         (unless (zerop end)
193           (send-to-emacs `(:read-output ,(subseq (sos.buffer stream) 0 end)))           (funcall (sos.output-fn stream) (subseq (sos.buffer stream) 0 end))
194           (setf (sos.index stream) 0))))           (setf (sos.index stream) 0))))
195      (:charpos (sos.column stream))      (:charpos (sos.column stream))
196      (:line-length 75)      (:line-length 75)
197      (:file-position nil)      (:file-position nil)
# Line 135  The request is read from the socket as a Line 201  The request is read from the socket as a
201      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
203  (defstruct (slime-input-stream  (defstruct (slime-input-stream
204               (:include string-stream               (:include string-stream
205                         (lisp::in #'sis/in)                         (lisp::in #'sis/in)
206                         (lisp::misc #'sis/misc))                         (lisp::misc #'sis/misc))
207               (:conc-name sis.)               (:conc-name sis.)
208               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
209    (buffer "" :type string)               (:constructor make-slime-input-stream (input-fn sos)))
210    (index 0 :type kernel:index))    (input-fn nil :type function)
211      ;; We know our sibling output stream, so that we can force it before
212      ;; requesting input.
213      (sos      nil :type slime-output-stream)
214      (buffer   ""  :type string)
215      (index    0   :type kernel:index))
217  (defun sis/in (stream eof-errorp eof-value)  (defun sis/in (stream eof-errorp eof-value)
218    (declare (ignore eof-errorp eof-value))    (declare (ignore eof-errorp eof-value))
219    (let ((index (sis.index stream))    (let ((index (sis.index stream))
220          (buffer (sis.buffer stream)))          (buffer (sis.buffer stream)))
221      (when (= index (length buffer))      (when (= index (length buffer))
222        (setf buffer (slime-read-string))        (force-output (sis.sos stream))
223          (setf buffer (funcall (sis.input-fn stream)))
224        (setf (sis.buffer stream) buffer)        (setf (sis.buffer stream) buffer)
225        (setf index 0))        (setf index 0))
226      (prog1 (aref buffer index)      (prog1 (aref buffer index)
# Line 162  The request is read from the socket as a Line 234  The request is read from the socket as a
234      (:unread (setf (aref (sis.buffer stream)      (:unread (setf (aref (sis.buffer stream)
235                           (decf (sis.index stream)))                           (decf (sis.index stream)))
236                     arg1))                     arg1))
237      (:clear-input (setf (sis.index stream) 0      (:clear-input
238         (setf (sis.index stream) 0
239                          (sis.buffer stream) ""))                          (sis.buffer stream) ""))
240      (:listen (< (sis.index stream) (length (sis.buffer stream))))      (:listen (< (sis.index stream) (length (sis.buffer stream))))
241      (:charpos nil)      (:charpos nil)
# Line 174  The request is read from the socket as a Line 247  The request is read from the socket as a
248  ;;;; Compilation Commands  ;;;; Compilation Commands
 (defvar *swank-source-info* nil  
   "Bound to a SOURCE-INFO object during compilation.")  
250  (defvar *previous-compiler-condition* nil  (defvar *previous-compiler-condition* nil
251    "Used to detect duplicates.")    "Used to detect duplicates.")
253  (defvar *previous-context* nil  (defvar *previous-context* nil
254    "Previous compiler error context.")    "Previous compiler error context.")
 (defvar *compiler-notes* '()  
   "List of compiler notes for the last compilation unit.")  
256  (defvar *buffer-name* nil)  (defvar *buffer-name* nil)
257  (defvar *buffer-start-position* nil)  (defvar *buffer-start-position* nil)
258  (defvar *buffer-substring* nil)  (defvar *buffer-substring* nil)
 (defvar *compile-filename* nil)  
261  ;;;;; Trapping notes  ;;;;; Trapping notes
267  craft our own error messages, which can omit a lot of redundant  craft our own error messages, which can omit a lot of redundant
268  information."  information."
269    (unless (eq condition *previous-compiler-condition*)    (unless (eq condition *previous-compiler-condition*)
270      (let ((context (or (c::find-error-context nil) *previous-context*)))      (let ((context (c::find-error-context nil)))
271        (setq *previous-compiler-condition* condition)        (setq *previous-compiler-condition* condition)
272        (setq *previous-context* context)        (setq *previous-context* context)
273        (signal-compiler-condition condition context))))        (signal-compiler-condition condition context))))
# Line 211  information." Line 277  information."
277             'compiler-condition             'compiler-condition
278             :original-condition condition             :original-condition condition
279             :severity (severity-for-emacs condition)             :severity (severity-for-emacs condition)
280             :message (brief-compiler-message-for-emacs condition context)             :short-message (brief-compiler-message-for-emacs condition)
281               :message (long-compiler-message-for-emacs condition context)
282             :location (compiler-note-location context))))             :location (compiler-note-location context))))
284  (defun severity-for-emacs (condition)  (defun severity-for-emacs (condition)
# Line 221  information." Line 288  information."
288      (c::style-warning :note)      (c::style-warning :note)
289      (c::warning :warning)))      (c::warning :warning)))
291  (defun brief-compiler-message-for-emacs (condition error-context)  (defun brief-compiler-message-for-emacs (condition)
292    "Briefly describe a compiler error for Emacs.    "Briefly describe a compiler error for Emacs.
293  When Emacs presents the message it already has the source popped up  When Emacs presents the message it already has the source popped up
294  and the source form highlighted. This makes much of the information in  and the source form highlighted. This makes much of the information in
295  the error-context redundant."  the error-context redundant."
296      (princ-to-string condition))
298    (defun long-compiler-message-for-emacs (condition error-context)
299      "Describe a compiler error for Emacs including context information."
300    (declare (type (or c::compiler-error-context null) error-context))    (declare (type (or c::compiler-error-context null) error-context))
301    (multiple-value-bind (enclosing source)    (multiple-value-bind (enclosing source)
302        (if error-context        (if error-context
# Line 234  the error-context redundant." Line 305  the error-context redundant."
305      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"
306              enclosing source condition)))              enclosing source condition)))
308  (defun compiler-note-location (context)  (defun compiler-note-location (context)
309    (cond (context    (cond (context
310           (resolve-note-location           (resolve-note-location
# Line 270  the error-context redundant." Line 340  the error-context redundant."
340                                    (pos (eql nil))                                    (pos (eql nil))
341                                    (path (eql nil))                                    (path (eql nil))
342                                    (source (eql nil)))                                    (source (eql nil)))
343    (cond (buffer    (list :error "No error location available"))
344           (make-location (list :buffer buffer)  
345                          (list :position *buffer-start-position*)))  (defimplementation call-with-compilation-hooks (function)
346          (*compile-file-truename*    (let ((*previous-compiler-condition* nil)
347           (make-location (list :file (namestring *compile-file-truename*))          (*previous-context* nil)
348                          (list :position 0)))          (*print-readably* nil))
          (make-location (list :file *compile-filename*) (list :position 0)))  
          (list :error "No error location available"))))  
 (defmacro with-compilation-hooks (() &body body)  
   "Execute BODY and record the set of compiler notes."  
   `(let ((*previous-compiler-condition* nil)  
          (*previous-context* nil)  
          (*print-readably* nil))  
349      (handler-bind ((c::compiler-error #'handle-notification-condition)      (handler-bind ((c::compiler-error #'handle-notification-condition)
350                     (c::style-warning  #'handle-notification-condition)                     (c::style-warning  #'handle-notification-condition)
351                     (c::warning        #'handle-notification-condition))                     (c::warning        #'handle-notification-condition))
352        ,@body)))        (funcall function))))
354  (defmethod compile-file-for-emacs (filename load-p)  (defimplementation swank-compile-file (filename load-p)
355    (clear-xref-info filename)    (clear-xref-info filename)
356    (with-compilation-hooks ()    (with-compilation-hooks ()
357      (let ((*buffer-name* nil)      (let ((*buffer-name* nil))
358            (*compile-filename* filename))        (compile-file filename :load load-p))))
         (compile-file filename :load load-p))))  
360  (defmethod compile-string-for-emacs (string &key buffer position)  (defimplementation swank-compile-string (string &key buffer position)
361    (with-compilation-hooks ()    (with-compilation-hooks ()
362      (let ((*package* *buffer-package*)      (let ((*buffer-name* buffer)
           (*compile-filename* nil)  
           (*buffer-name* buffer)  
363            (*buffer-start-position* position)            (*buffer-start-position* position)
364            (*buffer-substring* string))            (*buffer-substring* string))
365        (with-input-from-string (stream string)        (with-input-from-string (stream string)
# Line 315  the error-context redundant." Line 372  the error-context redundant."
373  ;;;; XREF  ;;;; XREF
375  (defun lookup-xrefs (finder name)  (defmacro defxref (name function)
376    (xref-results-for-emacs (funcall finder (from-string name))))    `(defimplementation ,name (name)
377        (xref-results (,function name))))
378  (defslimefun who-calls (function-name)  
379    "Return the places where FUNCTION-NAME is called."  (defxref who-calls      xref:who-calls)
380    (lookup-xrefs #'xref:who-calls function-name))  (defxref who-references xref:who-references)
381    (defxref who-binds      xref:who-binds)
382  (defslimefun who-references (variable)  (defxref who-sets       xref:who-sets)
   "Return the places where the global variable VARIABLE is referenced."  
   (lookup-xrefs #'xref:who-references variable))  
 (defslimefun who-binds (variable)  
   "Return the places where the global variable VARIABLE is bound."  
   (lookup-xrefs #'xref:who-binds variable))  
 (defslimefun who-sets (variable)  
   "Return the places where the global variable VARIABLE is set."  
   (lookup-xrefs #'xref:who-sets variable))  
384  #+cmu19  #+cmu19
385  (progn  (progn
386    (defslimefun who-macroexpands (macro)    (defxref who-macroexpands xref:who-macroexpands)
387      "Return the places where MACRO is expanded."    ;; XXX
388      (lookup-xrefs #'xref:who-macroexpands macro))    (defimplementation who-specializes (symbol)
389        (let* ((methods (xref::who-specializes (find-class symbol)))
390    (defslimefun who-specializes (class)             (locations (mapcar #'method-location methods)))
391      "Return the methods with specializers for CLASS."        (mapcar #'list methods locations))))
392      (let* ((methods (xref::who-specializes (find-class (from-string class))))  
393             (locations (mapcar #'method-source-location methods)))  (defun xref-results (contexts)
394        (group-xrefs (mapcar (lambda (m l)    (mapcar (lambda (xref)
395                               (cons (let ((*print-pretty* nil))              (list (xref:xref-context-name xref)
396                                       (to-string m))                    (resolve-xref-location xref)))
397                                     l))            contexts))
                            methods locations))))  
399  (defun resolve-xref-location (xref)  (defun resolve-xref-location (xref)
400    (let ((name (xref:xref-context-name xref))    (let ((name (xref:xref-context-name xref))
# Line 363  the error-context redundant." Line 408  the error-context redundant."
408             (make-location (list :file (unix-truename file))             (make-location (list :file (unix-truename file))
409                            (list :function-name (string name))))                            (list :function-name (string name))))
410            (t            (t
411             `(:error ,(format nil "Unkown source location: ~S ~S ~S "             `(:error ,(format nil "Unknown source location: ~S ~S ~S "
412                               name file source-path))))))                               name file source-path))))))
 (defun xref-results-for-emacs (contexts)  
   "Prepare a list of xref contexts for Emacs.  
 The result is a list of xrefs:  
 group       ::= (FILENAME . ({reference}+))  
   (let ((xrefs '()))  
     (dolist (cxt contexts)  
       (let ((name (xref:xref-context-name cxt)))  
         (push (cons (to-string name)  
                     (resolve-xref-location cxt))  
     (group-xrefs xrefs)))  
 (defun location-buffer= (location1 location2)  
   (equalp location1 location2))  
 (defun file-xrefs-for-emacs (unix-filename contexts)  
   "Return a summary of the references from a particular file.  
 The result is a list of the form (FILENAME ((REFERRER SOURCE-PATH) ...))"  
   (list unix-filename  
         (loop for context in (sort-contexts-by-source-path contexts)  
               collect (list (let ((*print-pretty* nil))  
                               (to-string (xref:xref-context-name context)))  
                             (xref:xref-context-source-path context)))))  
 (defun sort-contexts-by-source-path (contexts)  
   "Sort xref contexts by lexical position of source-paths.  
 It is assumed that all contexts belong to the same file."  
   (sort contexts #'source-path< :key #'xref:xref-context-source-path))  
 (defun source-path< (path1 path2)  
   "Return true if PATH1 is lexically before PATH2."  
   (and (every #'< path1 path2)  
        (< (length path1) (length path2))))  
414  (defun clear-xref-info (namestring)  (defun clear-xref-info (namestring)
415    "Clear XREF notes pertaining to FILENAME.    "Clear XREF notes pertaining to NAMESTRING.
416  This is a workaround for a CMUCL bug: XREF records are cumulative."  This is a workaround for a CMUCL bug: XREF records are cumulative."
417    (let ((filename (parse-namestring namestring)))    (when c:*record-xref-info*
418      (when c:*record-xref-info*      (let ((filename (truename namestring)))
419        (dolist (db (list xref::*who-calls*        (dolist (db (list xref::*who-calls*
420                          #+cmu19 xref::*who-is-called*                          #+cmu19 xref::*who-is-called*
421                          #+cmu19 xref::*who-macroexpands*                          #+cmu19 xref::*who-macroexpands*
# Line 415  This is a workaround for a CMUCL bug: XR Line 423  This is a workaround for a CMUCL bug: XR
423                          xref::*who-binds*                          xref::*who-binds*
424                          xref::*who-sets*))                          xref::*who-sets*))
425          (maphash (lambda (target contexts)          (maphash (lambda (target contexts)
426                       ;; XXX update during traversal?
427                     (setf (gethash target db)                     (setf (gethash target db)
428                           (delete-if                           (delete filename contexts
429                            (lambda (ctx)                                   :key #'xref:xref-context-file
430                              (xref-context-derived-from-p ctx filename))                                   :test #'equalp)))
431                   db)))))                   db)))))
 (defun xref-context-derived-from-p (context filename)  
   (let ((xref-file (xref:xref-context-file context)))  
     (and xref-file (pathname= filename xref-file))))  
 (defun pathname= (&rest pathnames)  
   "True if PATHNAMES refer to the same file."  
   (apply #'string= (mapcar #'unix-truename pathnames)))  
433  (defun unix-truename (pathname)  (defun unix-truename (pathname)
434    (ext:unix-namestring (truename pathname)))    (ext:unix-namestring (truename pathname)))
# Line 499  constant pool." Line 499  constant pool."
499      (map-caller-code-components function spaces      (map-caller-code-components function spaces
500                                  (lambda (code) (push code referrers)))                                  (lambda (code) (push code referrers)))
501      referrers))      referrers))
503  (defun debug-info-definitions (debug-info)  (defun debug-info-definitions (debug-info)
504    "Return the defintions for a debug-info.  This should only be used    "Return the defintions for a debug-info.  This should only be used
505  for code-object without entry points, i.e., byte compiled  for code-object without entry points, i.e., byte compiled
# Line 512  code (are theree others?)" Line 512  code (are theree others?)"
512      (destructuring-bind (first) source      (destructuring-bind (first) source
513        (ecase (c::debug-source-from first)        (ecase (c::debug-source-from first)
514          (:file          (:file
515           (list           (list (list name
516            (cons name                       (make-location
517                  (make-location                        (list :file (unix-truename (c::debug-source-name first)))
518                   (list :file (unix-truename (c::debug-source-name first)))                        (list :function-name name)))))))))
                  (list :function-name name)))))))))  
520  (defun code-component-entry-points (code)  (defun code-component-entry-points (code)
521    "Return a list ((NAME . LOCATION) ...) of function definitons for    "Return a list ((NAME LOCATION) ...) of function definitons for
522  the code omponent CODE."  the code omponent CODE."
523    (delete-duplicates    (delete-duplicates
524     (loop for e = (kernel:%code-entry-points code)     (loop for e = (kernel:%code-entry-points code)
525           then (kernel::%function-next e)           then (kernel::%function-next e)
526           while e           while e
527           collect (cons (to-string (kernel:%function-name e))           collect (list (kernel:%function-name e)
528                         (function-source-location e)))                         (function-location e)))
529     :test #'equal))     :test #'equal))
531  (defslimefun list-callers (symbol-name)  (defimplementation list-callers (symbol)
532    "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."    "Return a list ((NAME LOCATION) ...) of callers."
533    (let ((components (function-callers (from-string symbol-name)))    (let ((components (function-callers symbol))
534          (xrefs '()))          (xrefs '()))
535      (dolist (code components)      (dolist (code components)
536        (let* ((entry (kernel:%code-entry-points code))        (let* ((entry (kernel:%code-entry-points code))
# Line 541  the code omponent CODE." Line 540  the code omponent CODE."
540                         (debug-info-definitions                         (debug-info-definitions
541                          (kernel:%code-debug-info code)))))                          (kernel:%code-debug-info code)))))
542          (setq xrefs (nconc defs xrefs))))          (setq xrefs (nconc defs xrefs))))
543      (group-xrefs xrefs)))      xrefs))
545    (defimplementation list-callees (symbol)
546      (let ((fns (function-callees symbol)))
547        (mapcar (lambda (fn)
548                  (list (kernel:%function-name fn)
549                        (function-location fn)))
550                fns)))
552  (defslimefun list-callees (symbol-name)  
   (let ((fns (function-callees (from-string symbol-name))))  
     (group-xrefs (mapcar (lambda (fn)  
                            (cons (to-string (kernel:%function-name fn))  
                                  (function-source-location fn)))  
553  ;;;; Definitions  ;;;; Definitions
555  (defvar *debug-definition-finding* t  (defvar *debug-definition-finding* nil
556    "When true don't handle errors while looking for definitions.    "When true don't handle errors while looking for definitions.
557  This is useful when debugging the definition-finding code.")  This is useful when debugging the definition-finding code.")
559    (defvar *source-snippet-size* 256
560      "Maximum number of characters in a snippet of source code.
561    Snippets at the beginning of definitions are used to tell Emacs what
562    the definitions looks like, so that it can accurately find them by
563    text search.")
565    (defvar *cache-sourcecode* t
566      "When true complete source files are cached.
567    The cache is used to keep known good copies of the source text which
568    correspond to the loaded code. Finding definitions is much more
569    reliable when the exact source is available, so we cache it incase it
570    gets edited on disk later.")
572    (defvar *source-file-cache* (make-hash-table :test 'equal)
573      "Cache of source file contents.
574    Maps from truename to source-cache-entry structure.")
576    (defstruct (source-cache-entry
577                 (:conc-name source-cache-entry.)
578                 (:constructor make-source-cache-entry (text date)))
579      text date)
581    (defun source-cache-get (filename date)
582      "Return the source code for FILENAME written on DATE as a string.
583    Return NIL if the right version cannot be found."
584      (let ((entry (gethash filename *source-file-cache*)))
585        (cond ((and entry (equal date (source-cache-entry.date entry)))
586               ;; Cache hit.
587               (source-cache-entry.text entry))
588              ((or (null entry)
589                   (not (equal date (source-cache-entry.date entry))))
590               ;; Cache miss.
591               (if (equal (file-write-date filename) date)
592                   ;; File on disk has the correct version.
593                   (with-open-file (s filename :direction :input)
594                     (let ((string (make-string (file-length s))))
595                       (read-sequence string s)
596                       (setf (gethash filename *source-file-cache*)
597                             (make-source-cache-entry string date))
598                       string))
599                   nil)))))
601  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
602    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY ignoring errors.  Return the source location returned
603  returned by BODY or if an error occurs a description of the error.  by BODY or if an error occurs a description of the error.  The second
604  The second return value is the condition or nil."  return value is the condition or nil."
605    `(flet ((body () ,@body))    `(flet ((body () ,@body))
606      (if *debug-definition-finding*      (if *debug-definition-finding*
607          (body)          (body)
608          (handler-case (values (progn ,@body) nil)          (handler-case (values (progn ,@body) nil)
609            (error (c) (values (list :error (princ-to-string c)) c))))))            (error (c) (values (list :error (princ-to-string c)) c))))))
611  (defun function-first-code-location (function)  (defun function-first-code-location (function)
612    (and (function-has-debug-function-p function)    (and (function-has-debug-function-p function)
613         (di:debug-function-start-location         (di:debug-function-start-location
# Line 580  The second return value is the condition Line 621  The second return value is the condition
621             (vm::find-code-object function))             (vm::find-code-object function))
622         (not (eq closure function))))         (not (eq closure function))))
624    (defun genericp (fn)
625      (typep fn 'generic-function))
627  (defun struct-closure-p (function)  (defun struct-closure-p (function)
628    (or (function-code-object= function #'kernel::structure-slot-accessor)    (or (function-code-object= function #'kernel::structure-slot-accessor)
629        (function-code-object= function #'kernel::structure-slot-setter)        (function-code-object= function #'kernel::structure-slot-setter)
# Line 598  The second return value is the condition Line 642  The second return value is the condition
642              function)))              function)))
643      (kernel:layout-info (find-layout function))))      (kernel:layout-info (find-layout function))))
645  (defun dd-source-location (dd)  (defun dd-location (dd)
646    (let ((constructor (or (kernel:dd-default-constructor dd)    (let ((constructor (or (kernel:dd-default-constructor dd)
647                           (car (kernel::dd-constructors dd)))))                           (car (kernel::dd-constructors dd)))))
648      (when (or (not constructor) (and (consp constructor)      (when (or (not constructor) (and (consp constructor)
649                                       (not (car constructor))))                                       (not (car constructor))))
650        (error "Cannot locate struct without constructor: ~S"        (error "Cannot locate struct without constructor: ~S"
651               (kernel::dd-name dd)))               (kernel::dd-name dd)))
652      (function-source-location      (function-location
653       (coerce (if (consp constructor) (car constructor) constructor)       (coerce (if (consp constructor) (car constructor) constructor)
654               'function))))               'function))))
656  (defun genericp (fn)  (defun function-location (function)
657    (typep fn 'generic-function))    "Return the source location for FUNCTION."
 (defun gf-definition-location (gf)  
   (flet ((guess-source-file (faslfile)  
             (merge-pathnames (make-pathname :type "lisp")  
     (let ((def-source (pcl::definition-source gf))  
           (name (string (pcl:generic-function-name gf))))  
       (etypecase def-source  
         (pathname (make-location  
                    `(:file ,(guess-source-file def-source))  
                    `(:function-name ,name)))  
          (destructuring-bind ((dg name) pathname) def-source  
            (declare (ignore dg))  
            (etypecase pathname  
               (make-location `(:file ,(guess-source-file pathname))  
                              `(:function-name ,(string name)))))))))))  
 (defun method-source-location (method)  
   (function-source-location (or (pcl::method-fast-function method)  
                                 (pcl:method-function method))))  
 (defun gf-method-locations (gf)  
   (let ((ms (pcl::generic-function-methods gf)))  
     (mapcar #'method-source-location ms)))  
 (defun gf-source-locations (gf)  
   (list* (gf-definition-location gf)  
          (gf-method-locations gf)))  
 (defun function-source-locations (function)  
   "Return a list of source locations for FUNCTION."  
658    ;; First test if FUNCTION is a closure created by defstruct; if so    ;; First test if FUNCTION is a closure created by defstruct; if so
659    ;; extract the defstruct-description (dd) from the closure and find    ;; extract the defstruct-description (dd) from the closure and find
660    ;; the constructor for the struct.  Defstruct creates a defun for    ;; the constructor for the struct.  Defstruct creates a defun for
# Line 654  The second return value is the condition Line 664  The second return value is the condition
664    ;; For an ordinary function we return the source location of the    ;; For an ordinary function we return the source location of the
665    ;; first code-location we find.    ;; first code-location we find.
666    (cond ((struct-closure-p function)    (cond ((struct-closure-p function)
667           (list           (safe-definition-finding
668            (safe-definition-finding            (dd-location (struct-closure-dd function))))
            (dd-source-location (struct-closure-dd function)))))  
669          ((genericp function)          ((genericp function)
670           (gf-source-locations function))           (gf-location function))
671          (t          (t
672           (list           (multiple-value-bind (code-location error)
673            (multiple-value-bind (code-location error)               (safe-definition-finding (function-first-code-location function))
674                (safe-definition-finding (function-first-code-location function))             (cond (error (list :error (princ-to-string error)))
675              (cond (error (list :error (princ-to-string error)))                   (t (code-location-source-location code-location)))))))
676                    (t (code-location-source-location code-location))))))))  
677    ;; XXX maybe special case setters/getters
678  (defun function-source-location (function)  (defun method-location (method)
679    (destructuring-bind (first) (function-source-locations function)    (function-location (or (pcl::method-fast-function method)
680      first))                           (pcl:method-function method))))
682  (defslimefun find-function-locations (symbol-name)  (defun method-dspec (method)
683    "Return a list of source-locations for SYMBOL-NAME's functions."    (let* ((gf (pcl:method-generic-function method))
684    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)           (name (pcl:generic-function-name gf))
685      (cond ((not foundp)           (specializers (pcl:method-specializers method))
686             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))           (qualifiers (pcl:method-qualifiers method)))
687            ((macro-function symbol)      `(method ,name ,@qualifiers ,(pcl::unparse-specializers specializers))))
688             (function-source-locations (macro-function symbol)))  
689            ((special-operator-p symbol)  (defun method-definition (method)
690             (list (list :error (format nil "~A is a special-operator" symbol))))    (list (method-dspec method)
691            ((fboundp symbol)          (method-location method)))
692             (function-source-locations (coerce symbol 'function)))  
693            (t (list (list :error  (defun gf-location (gf)
694                           (format nil "Symbol not fbound: ~A" symbol-name))))    (definition-source-location gf (pcl::generic-function-name gf)))
695            )))  
696    (defun gf-method-definitions (gf)
697      (mapcar #'method-definition (pcl::generic-function-methods gf)))
699    (defun function-definitions (name)
700      "Return definitions for NAME in the \"function namespace\", i.e.,
701    regular functions, generic functions, methods and macros.
702    NAME can any valid function name (e.g, (setf car))."
703      (cond ((and (symbolp name) (macro-function name))
704             (list `((defmacro ,name)
705                     ,(function-location (macro-function name)))))
706            ((and (symbolp name) (special-operator-p name))
707             (list `((:special-operator ,name)
708                     (:error ,(format nil "Special operator: ~S" name)))))
709            ((and (ext:valid-function-name-p name)
710                  (ext:info :function :definition name))
711             (let ((function (coerce name 'function)))
712               (cond ((genericp function)
713                      (cons (list `(defgeneric ,name)
714                                  (function-location function))
715                            (gf-method-definitions function)))
716                     (t (list (list `(function ,name)
717                                    (function-location function)))))))))
719    (defun maybe-make-definition (function kind name)
720      (if function
721          (list (list `(,kind ,name) (function-location function)))))
723    (defun type-definitions (name)
724      (maybe-make-definition (ext:info :type :expander name) 'deftype name))
726    (defun find-dd (name)
727      (let ((layout (ext:info :type :compiler-layout name)))
728        (if layout
729            (kernel:layout-info layout))))
731    (defun condition-class-location (class)
732      (let ((slots (conditions::condition-class-slots class))
733            (name (conditions::condition-class-name class)))
734        (cond ((null slots)
735               `(:error ,(format nil "No location info for condition: ~A" name)))
736              (t
737               (let* ((slot (first slots))
738                      (gf (fdefinition
739                           (first (conditions::condition-slot-readers slot)))))
740                 (method-location
741                  (first
742                   (pcl:compute-applicable-methods-using-classes
743                    gf (list (find-class name))))))))))
745    (defun class-location (class)
746      (definition-source-location class (pcl:class-name class)))
748    (defun make-name-in-file-location (file string)
749      (multiple-value-bind (filename c)
750          (ignore-errors
751            (unix-truename (merge-pathnames (make-pathname :type "lisp")
752                                            file)))
753        (cond (filename (make-location `(:file ,filename)
754                                       `(:function-name ,string)))
755              (t (list :error (princ-to-string c))))))
757    (defun source-location-form-numbers (location)
758      (c::decode-form-numbers (c::form-numbers-form-numbers location)))
760    (defun source-location-tlf-number (location)
761      (nth-value 0 (source-location-form-numbers location)))
763    (defun source-location-form-number (location)
764      (nth-value 1 (source-location-form-numbers location)))
766    (defun resolve-file-source-location (location)
767      (let ((filename (c::file-source-location-pathname location))
768            (tlf-number (source-location-tlf-number location))
769            (form-number (source-location-form-number location)))
770        (with-open-file (s filename)
771          (let ((pos (form-number-stream-position tlf-number form-number s)))
772            (make-location `(:file ,(unix-truename filename))
773                           `(:position ,(1+ pos)))))))
775    (defun resolve-stream-source-location (location)
776      (let ((info (c::stream-source-location-user-info location))
777            (tlf-number (source-location-tlf-number location))
778            (form-number (source-location-form-number location)))
779        ;; XXX duplication in frame-source-location
780        (assert (info-from-emacs-buffer-p info))
781        (destructuring-bind (&key emacs-buffer emacs-buffer-string
782                                  emacs-buffer-offset) info
783          (with-input-from-string (s emacs-buffer-string)
784            (let ((pos (form-number-stream-position tlf-number form-number s)))
785              (make-location `(:buffer ,emacs-buffer)
786                             `(:position ,(+ emacs-buffer-offset pos))))))))
788    (defun file-source-location-p (object)
789      (when (fboundp 'c::file-source-location-p)
790        (c::file-source-location-p object)))
792    (defun stream-source-location-p (object)
793      (when (fboundp 'c::stream-source-location-p)
794        (c::stream-source-location-p object)))
796    (defun definition-source-location (object name)
797      (let ((source (pcl::definition-source object)))
798        (etypecase source
799          (null
800           `(:error ,(format nil "No source info for: ~A" object)))
801          ((satisfies file-source-location-p)
802           (resolve-file-source-location source))
803          ((satisfies stream-source-location-p)
804           (resolve-stream-source-location source))
805          (pathname
806           (make-name-in-file-location source name))
807          (cons
808           (destructuring-bind ((dg name) pathname) source
809             (declare (ignore dg))
810             (etypecase pathname
811               (pathname (make-name-in-file-location pathname (string name)))
812               (null `(:error ,(format nil "Cannot resolve: ~S" source)))))))))
814    (defun class-definitions (name)
815      (if (symbolp name)
816          (let ((class (kernel::find-class name nil)))
817            (etypecase class
818              (null '())
819              (kernel::structure-class
820               (list (list `(defstruct ,name) (dd-location (find-dd name)))))
821              #+(or)
822              (conditions::condition-class
823               (list (list `(define-condition ,name)
824                           (condition-class-location class))))
825              (kernel::standard-class
826               (list (list `(defclass ,name)
827                           (class-location (find-class name)))))
828              ((or kernel::built-in-class conditions::condition-class)
829               (list (list `(kernel::define-type-class ,name)
830                           `(:error
831                             ,(format nil "No source info for ~A" name)))))))))
833    (defun setf-definitions (name)
834      (let ((function (or (ext:info :setf :inverse name)
835                          (ext:info :setf :expander name))))
836        (if function
837            (list (list `(setf ,name)
838                        (function-location (coerce function 'function)))))))
840    (defun compiler-macro-definitions (symbol)
841      (maybe-make-definition (compiler-macro-function symbol)
842                             'define-compiler-macro
843                             symbol))
845    (defun source-transform-definitions (name)
846      (maybe-make-definition (ext:info :function :source-transform name)
847                             'c:def-source-transform
848                             name))
850    (defun function-info-definitions (name)
851      (let ((info (ext:info :function :info name)))
852        (if info
853            (append (loop for transform in (c::function-info-transforms info)
854                          collect (list `(c:deftransform ,name
855                                          ,(c::type-specifier
856                                            (c::transform-type transform)))
857                                        (function-location (c::transform-function
858                                                            transform))))
859                    (maybe-make-definition (c::function-info-derive-type info)
860                                           'c::derive-type name)
861                    (maybe-make-definition (c::function-info-optimizer info)
862                                           'c::optimizer name)
863                    (maybe-make-definition (c::function-info-ltn-annotate info)
864                                           'c::ltn-annotate name)
865                    (maybe-make-definition (c::function-info-ir2-convert info)
866                                           'c::ir2-convert name)
867                    (loop for template in (c::function-info-templates info)
868                          collect (list `(c::vop ,(c::template-name template))
869                                        (function-location
870                                         (c::vop-info-generator-function
871                                          template))))))))
873    (defun ir1-translator-definitions (name)
874      (maybe-make-definition (ext:info :function :ir1-convert name)
875                             'c:def-ir1-translator name))
877    (defimplementation find-definitions (name)
878      (append (function-definitions name)
879              (setf-definitions name)
880              (class-definitions name)
881              (type-definitions name)
882              (compiler-macro-definitions name)
883              (source-transform-definitions name)
884              (function-info-definitions name)
885              (ir1-translator-definitions name)))
887  ;;;; Documentation.  ;;;; Documentation.
889  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
890    (let ((result '()))    (let ((result '()))
891      (flet ((doc (kind)      (flet ((doc (kind)
892               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 734  The second return value is the condition Line 932  The second return value is the condition
932                         (doc nil)))                         (doc nil)))
933        result)))        result)))
935  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
936    (print-description-to-string    (ecase namespace
937     (or (ext:info setf inverse (from-string symbol-name))      (:variable
938         (ext:info setf expander (from-string symbol-name)))))       (describe symbol))
939        ((:function :generic-function)
940  (defslimefun describe-type (symbol-name)       (describe (symbol-function symbol)))
941    (print-description-to-string      (:setf
942     (kernel:values-specifier-type (from-string symbol-name))))       (describe (or (ext:info setf inverse symbol))
943                   (ext:info setf expander symbol)))
944  (defslimefun describe-class (symbol-name)      (:type
945    (print-description-to-string (find-class (from-string symbol-name) nil)))       (describe (kernel:values-specifier-type symbol)))
946        (:class
947  (defslimefun describe-alien-type (symbol-name)       (describe (find-class symbol)))
948    (let ((name (from-string symbol-name)))      (:alien-type
949      (ecase (ext:info :alien-type :kind name)       (ecase (ext:info :alien-type :kind symbol)
950        (:primitive         (:primitive
951         (print-description-to-string          (describe (let ((alien::*values-type-okay* t))
952          (let ((alien::*values-type-okay* t))                      (funcall (ext:info :alien-type :translator symbol)
953            (funcall (ext:info :alien-type :translator name) (list name)))))                               (list symbol)))))
954        ((:defined)         ((:defined)
955         (print-description-to-string (ext:info :alien-type :definition name)))          (describe (ext:info :alien-type :definition symbol)))
956        (:unknown         (:unknown
957         (format nil "Unkown alien type: ~A" symbol-name)))))          (format nil "Unkown alien type: ~S" symbol))))
958        (:alien-struct
959  (defmacro %describe-alien (symbol-name namespace)       (describe (ext:info :alien-type :struct symbol)))
960    `(print-description-to-string      (:alien-union
961      (ext:info :alien-type ,namespace (from-string ,symbol-name))))       (describe (ext:info :alien-type :union symbol)))
962        (:alien-enum
963  (defslimefun describe-alien-struct (symbol-name)       (describe (ext:info :alien-type :enum symbol)))))
964    (%describe-alien symbol-name :struct))  
965    (defun debug-variable-symbol-or-deleted (var)
966  (defslimefun describe-alien-union (symbol-name)    (etypecase var
967    (%describe-alien symbol-name :union))      (di:debug-variable
968         (di::debug-variable-symbol var))
969  (defslimefun describe-alien-enum (symbol-name)      ((member :deleted)
970    (%describe-alien symbol-name :enum))       '#:deleted)))
972  (defmethod arglist-string (fname)  (defun debug-function-arglist (debug-function)
973    "Return a string describing the argument list for FNAME.    (let ((args (di::debug-function-lambda-list debug-function))
974  The result has the format \"(...)\"."          (required '())
975    (declare (type string fname))          (optional '())
976    (multiple-value-bind (function condition)          (rest '())
977        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))          (key '()))
978      (when condition      ;; collect the names of debug-vars
979        (return-from arglist-string (format nil "(-- ~A)" condition)))      (dolist (arg args)
980      (let ((arglist        (etypecase arg
981             (if (not (or (fboundp function)          (di::debug-variable
982                          (functionp function)))           (push (di::debug-variable-symbol arg) required))
983                 "(-- <Unknown-Function>)"          ((member :deleted)
984                 (let* ((fun (or (macro-function function)           (push ':deleted required))
985                                 (symbol-function function)))          (cons
986                        (df (di::function-debug-function fun))           (ecase (car arg)
987                        (arglist (kernel:%function-arglist fun)))             (:keyword
988                   (cond ((eval:interpreted-function-p fun)              (push (second arg) key))
989                          (eval:interpreted-function-arglist fun))             (:optional
990                         ((pcl::generic-function-p fun)              (push (debug-variable-symbol-or-deleted (second arg)) optional))
991                          (pcl::gf-pretty-arglist fun))             (:rest
992                         (arglist arglist)              (push (debug-variable-symbol-or-deleted (second arg)) rest))))))
993                         ;; this should work both for      ;; intersperse lambda keywords as needed
994                         ;; compiled-debug-function and for      (append (nreverse required)
995                         ;; interpreted-debug-function              (if optional (cons '&optional (nreverse optional)))
996                         (df (di::debug-function-lambda-list df))              (if rest (cons '&rest (nreverse rest)))
997                         (t "(<arglist-unavailable>)"))))))              (if key (cons '&key (nreverse key))))))
998        (if (stringp arglist)  
999            arglist  (defun symbol-debug-function-arglist (fname)
1000            (to-string arglist)))))    "Return FNAME's debug-function-arglist and %function-arglist.
1001    A utility for debugging DEBUG-FUNCTION-ARGLIST."
1002      (let ((fn (fdefinition fname)))
1003        (values (debug-function-arglist (di::function-debug-function fn))
1004                (kernel:%function-arglist (kernel:%function-self fn)))))
1006    (defun read-arglist (fn)
1007      "Parse the arglist-string of the function object FN."
1008      (let ((string (kernel:%function-arglist
1009                     (kernel:%function-self fn)))
1010            (package (find-package
1011                      (c::compiled-debug-info-package
1012                       (kernel:%code-debug-info
1013                        (vm::find-code-object fn))))))
1014        (with-standard-io-syntax
1015          (let ((*package* (or package *package*)))
1016            (read-from-string string)))))
1018    (defimplementation arglist (symbol)
1019      (let* ((fun (or (macro-function symbol)
1020                      (symbol-function symbol)))
1021             (arglist
1022              (cond ((eval:interpreted-function-p fun)
1023                     (eval:interpreted-function-arglist fun))
1024                    ((pcl::generic-function-p fun)
1025                     (pcl:generic-function-lambda-list fun))
1026                    ((kernel:%function-arglist (kernel:%function-self fun))
1027                     (read-arglist fun))
1028                    ;; this should work both for
1029                    ;; compiled-debug-function and for
1030                    ;; interpreted-debug-function
1031                    (t
1032                     (handler-case (debug-function-arglist
1033                                    (di::function-debug-function fun))
1034                       (di:unhandled-condition () :not-available))))))
1035        (check-type arglist (or list (member :not-available)))
1036        arglist))
1039  ;;;; Miscellaneous.  ;;;; Miscellaneous.
1041  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
1042    (walker:macroexpand-all form))    (walker:macroexpand-all form))
1044  (defun tracedp (fname)  ;; (in-package :c)
1045    (gethash (debug::trace-fdefinition fname)  ;;
1046             debug::*traced-functions*))  ;; (defun swank-backend::expand-ir1-top-level (form)
1047    ;;   "A scaled down version of the first pass of the compiler."
1048  (defslimefun toggle-trace-fdefinition (fname-string)  ;;   (with-compilation-unit ()
1049    (let ((fname (from-string fname-string)))  ;;     (let* ((*lexical-environment*
1050      (cond ((tracedp fname)  ;;             (make-lexenv :default (make-null-environment)
1051             (debug::untrace-1 fname)  ;;                          :cookie *default-cookie*
1052             (format nil "~S is now untraced." fname))  ;;                          :interface-cookie *default-interface-cookie*))
1053            (t  ;;            (*source-info* (make-lisp-source-info form))
1054             (debug::trace-1 fname (debug::make-trace-info))  ;;            (*block-compile* nil)
1055             (format nil "~S is now traced." fname)))))  ;;            (*block-compile-default* nil))
1056    ;;       (with-ir1-namespace
1057    ;;           (clear-stuff)
1058    ;;         (find-source-paths form 0)
1059    ;;         (ir1-top-level form '(0) t)))))
1060    ;;
1061    ;; (in-package :swank-backend)
1062    ;;
1063    ;; (defun print-ir1-converted-blocks (form)
1064    ;;   (with-output-to-string (*standard-output*)
1065    ;;     (c::print-all-blocks (expand-ir1-top-level (from-string form)))))
1066    ;;
1067    ;; (defun print-compilation-trace (form)
1068    ;;   (with-output-to-string (*standard-output*)
1069    ;;     (with-input-from-string (s form)
1070    ;;       (ext:compile-from-stream s
1071    ;;                                :verbose t
1072    ;;                                :progress t
1073    ;;                                :trace-stream *standard-output*))))
1075  (defslimefun set-default-directory (directory)  (defimplementation set-default-directory (directory)
1076    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
1077    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
1078    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
1079    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
1080    (namestring (ext:default-directory)))    (namestring (ext:default-directory)))
1082    ;;; source-path-{stream,file,string,etc}-position moved into
1083  ;;;; Source-paths  ;;; swank-source-path-parser
 ;;; CMUCL uses a data structure called "source-path" to locate  
 ;;; subforms.  The compiler assigns a source-path to each form in a  
 ;;; compilation unit.  Compiler notes usually contain the source-path  
 ;;; of the error location.  
 ;;; Compiled code objects don't contain source paths, only the  
 ;;; "toplevel-form-number" and the (sub-) "form-number".  To get from  
 ;;; the form-number to the source-path we need the entire toplevel-form  
 ;;; (i.e. we have to read the source code).  CMUCL has already some  
 ;;; utilities to do this translation, but we use some extended  
 ;;; versions, because we need more exact position info.  Apparently  
 ;;; Hemlock is happy with the position of the toplevel-form; we also  
 ;;; need the position of subforms.  
 ;;; We use a special readtable to get the positions of the subforms.  
 ;;; The readtable stores the start and end position for each subform in  
 ;;; hashtable for later retrieval.  
 (defun make-source-recorder (fn source-map)  
   "Return a macro character function that does the same as FN, but  
 additionally stores the result together with the stream positions  
 before and after of calling FN in the hashtable SOURCE-MAP."  
   (lambda (stream char)  
     (let ((start (file-position stream))  
           (values (multiple-value-list (funcall fn stream char)))  
           (end (file-position stream)))  
       #+(or) (format t "~&[~D ~{~A~^, ~} ~D]~%" start values end)  
       (unless (null values)  
         (push (cons start end) (gethash (car values) source-map)))  
       (values-list values))))  
 (defun make-source-recording-readtable (readtable source-map)  
   "Return a source position recording copy of READTABLE.  
 The source locations are stored in SOURCE-MAP."  
   (let* ((tab (copy-readtable readtable))  
          (*readtable* tab))  
     (dotimes (code char-code-limit)  
       (let ((char (code-char code)))  
         (multiple-value-bind (fn term) (get-macro-character char tab)  
           (when fn  
             (set-macro-character char (make-source-recorder fn source-map)  
                                  term tab)))))  
 (defun make-source-map ()  
   (make-hash-table :test #'eq))  
 (defvar *source-map* (make-source-map)  
   "The hashtable table used for source position recording.")  
 (defvar *recording-readtable-cache* '()  
   "An alist of (READTABLE . RECORDING-READTABLE) pairs.")  
 (defun lookup-recording-readtable (readtable)  
   "Find a cached or create a new recording readtable for READTABLE."  
   (or (cdr (assoc readtable *recording-readtable-cache*))  
       (let ((table (make-source-recording-readtable readtable *source-map*)))  
         (push (cons readtable table) *recording-readtable-cache*)  
 (defun read-and-record-source-map (stream)  
   "Read the next object from STREAM.  
 Return the object together with a hashtable that maps  
 subexpressions of the object to stream positions."  
   (let ((*readtable* (lookup-recording-readtable *readtable*)))  
     (clrhash *source-map*)  
     (values (read stream) *source-map*)))  
 (defun source-path-stream-position (path stream)  
   "Search the source-path PATH in STREAM and return its position."  
   (destructuring-bind (tlf-number . path) path  
     (let ((*read-suppress* t))  
       (dotimes (i tlf-number) (read stream))  
       (multiple-value-bind (form source-map)  
           (read-and-record-source-map stream)  
         (source-path-source-position (cons 0 path) form source-map)))))  
 (defun source-path-string-position (path string)  
   (with-input-from-string (s string)  
     (source-path-stream-position path s)))  
 (defun source-path-file-position (path filename)  
   (with-open-file (file filename)  
     (source-path-stream-position path file)))  
 (defun source-path-source-position (path form source-map)  
   "Return the start position of PATH form FORM and SOURCE-MAP.  All  
 subforms along the path are considered and the start and end position  
 of deepest (i.e. smallest) possible form is returned."  
   ;; compute all subforms along path  
   (let ((forms (loop for n in path  
                      for f = form then (nth n f)  
                      collect f)))  
     ;; select the first subform present in source-map  
     (loop for form in (reverse forms)  
           for positions = (gethash form source-map)  
           until (and positions (null (cdr positions)))  
           finally (destructuring-bind ((start . end)) positions  
                     (return (values (1- start) end))))))  
1085  (defun code-location-stream-position (code-location stream)  (defun code-location-stream-position (code-location stream)
1086    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the
1087  toplevel-form-number and form-number from CODE-LOCATION and use that  toplevel-form-number and form-number from CODE-LOCATION and use that
1088  to find the position of the corresponding form."  to find the position of the corresponding form.
1090    Finish with STREAM positioned at the start of the code location."
1091    (let* ((location (debug::maybe-block-start-location code-location))    (let* ((location (debug::maybe-block-start-location code-location))
1092           (tlf-offset (di:code-location-top-level-form-offset location))           (tlf-offset (di:code-location-top-level-form-offset location))
1093           (form-number (di:code-location-form-number location))           (form-number (di:code-location-form-number location)))
1094           (*read-suppress* t))      (let ((pos (form-number-stream-position tlf-offset form-number stream)))
1095      (dotimes (i tlf-offset) (read stream))        (file-position stream pos)
1096          pos)))
1098    (defun form-number-stream-position (tlf-number form-number stream)
1099      (let ((*read-suppress* t))
1100        (dotimes (i tlf-number) (read stream))
1101      (multiple-value-bind (tlf position-map) (read-and-record-source-map stream)      (multiple-value-bind (tlf position-map) (read-and-record-source-map stream)
1102        (let* ((path-table (di:form-number-translations tlf 0))        (let* ((path-table (di:form-number-translations tlf 0))
1103               (source-path               (source-path
1104                (if (<= (length path-table) form-number) ; source out of sync?                (if (<= (length path-table) form-number) ; source out of sync?
1105                    (list 0)              ; should probably signal a condition                    (list 0)              ; should probably signal a condition
1106                    (reverse (cdr (aref path-table form-number))))))                    (reverse (cdr (aref path-table form-number))))))
1107          (source-path-source-position source-path tlf position-map)))))          (source-path-source-position source-path tlf position-map)))))
1109  (defun code-location-string-offset (code-location string)  (defun code-location-string-offset (code-location string)
1110    (with-input-from-string (s string)    (with-input-from-string (s string)
# Line 955  to find the position of the correspondin Line 1114  to find the position of the correspondin
1114    (with-open-file (s filename :direction :input)    (with-open-file (s filename :direction :input)
1115      (code-location-stream-position code-location s)))      (code-location-stream-position code-location s)))
1117    (defun info-from-emacs-buffer-p (info)
1118      (and info
1119           (consp info)
1120           (eq :emacs-buffer (car info))))
1122  (defun debug-source-info-from-emacs-buffer-p (debug-source)  (defun debug-source-info-from-emacs-buffer-p (debug-source)
1123    (let ((info (c::debug-source-info debug-source)))    (info-from-emacs-buffer-p (c::debug-source-info debug-source)))
     (and info  
          (consp info)  
          (eq :emacs-buffer (car info)))))  
1125  (defun source-location-from-code-location (code-location)  (defun source-location-from-code-location (code-location)
1126    "Return the source location for CODE-LOCATION."    "Return the source location for CODE-LOCATION."
# Line 971  to find the position of the correspondin Line 1132  to find the position of the correspondin
1132           (name (di:debug-source-name debug-source)))           (name (di:debug-source-name debug-source)))
1133      (ecase from      (ecase from
1134        (:file        (:file
1135         (make-location (list :file (unix-truename name))         (let* ((code-date (di:debug-source-created debug-source))
1136                        (list :position (1+ (code-location-file-position                (source (source-cache-get name code-date)))
1137                                             code-location name)))))           (if (null source)
1138                 ;; We don't have up-to-date sourcecode. Emacs will have
1139                 ;; to make a regexp search.
1140                 ;; XXX Leave position blank. Emacs will plug in the function name.
1141                 (make-location (list :file (unix-truename name)) nil)
1142                 (with-open-file (s name :direction :input)
1143                   (make-location (list :file (unix-truename name))
1144                                  (list :position
1145                                        (1+ (code-location-stream-position
1146                                             code-location s)))
1147                                  `(:snippet ,(read-snippet s)))))))
1148        (:stream        (:stream
1149         (assert (debug-source-info-from-emacs-buffer-p debug-source))         (assert (debug-source-info-from-emacs-buffer-p debug-source))
1150         (let ((info (c::debug-source-info debug-source)))         (let* ((info (c::debug-source-info debug-source))
1151                  (string (getf info :emacs-buffer-string))
1152                  (position (code-location-string-offset
1153                             code-location
1154                             string)))
1155           (make-location           (make-location
1156            (list :buffer (getf info :emacs-buffer))            (list :buffer (getf info :emacs-buffer))
1157            (list :position (+ (getf info :emacs-buffer-offset)            (list :position (+ (getf info :emacs-buffer-offset) position))
1158                               (code-location-string-offset            (list :snippet (with-input-from-string (s string)
1159                                code-location                          (file-position s position)
1160                                (getf info :emacs-buffer-string)))))))                          (read-snippet s))))))
1161        (:lisp        (:lisp
1162         (make-location         (make-location
1163          (list :source-form (with-output-to-string (*standard-output*)          (list :source-form (with-output-to-string (*standard-output*)
# Line 995  to find the position of the correspondin Line 1170  to find the position of the correspondin
1170    (safe-definition-finding    (safe-definition-finding
1171     (source-location-from-code-location code-location)))     (source-location-from-code-location code-location)))
1173  (defslimefun getpid ()  (defun read-snippet (stream)
1174    (unix:unix-getpid))    (read-upto-n-chars stream *source-snippet-size*))
1176    (defun read-upto-n-chars (stream n)
1177      "Return a string of upto N chars from STREAM."
1178      (let* ((string (make-string n))
1179             (chars  (read-sequence string stream)))
1180        (subseq string 0 chars)))
1183  ;;;; Debugging  ;;;; Debugging
1185  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
1187  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
1188    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
1189    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
1190           (*sldb-restarts* (compute-restarts *swank-debugger-condition*))           (debug:*stack-top-hint* nil))
          (debug:*stack-top-hint* nil)  
          (*debugger-hook* nil)  
          (*readtable* (or debug:*debug-readtable* *readtable*))  
          (*print-level* debug:*debug-print-level*)  
          (*print-length* debug:*debug-print-length*)  
          (*print-readably* nil))  
1191      (handler-bind ((di:debug-condition      (handler-bind ((di:debug-condition
1192                      (lambda (condition)                      (lambda (condition)
1193                        (signal (make-condition                        (signal (make-condition
# Line 1021  to find the position of the correspondin Line 1195  to find the position of the correspondin
1195                                 :original-condition condition)))))                                 :original-condition condition)))))
1196        (funcall debugger-loop-fn))))        (funcall debugger-loop-fn))))
 (defun format-restarts-for-emacs ()  
   "Return a list of restarts for *swank-debugger-condition* in a  
 format suitable for Emacs."  
   (loop for restart in *sldb-restarts*  
         collect (list (princ-to-string (restart-name restart))  
                       (princ-to-string restart))))  
 (defun format-condition-for-emacs ()  
   (format nil "~A~%   [Condition of type ~S]"  
           (debug::safe-condition-message *swank-debugger-condition*)  
           (type-of *swank-debugger-condition*)))  
1198  (defun nth-frame (index)  (defun nth-frame (index)
1199    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (di:frame-down frame))
1200         (i index (1- i)))         (i index (1- i)))
1201        ((zerop i) frame)))        ((zerop i) frame)))
1203  (defun nth-restart (index)  (defimplementation compute-backtrace (start end)
   (nth index *sldb-restarts*))  
 (defun format-frame-for-emacs (frame)  
   (list (di:frame-number frame)  
         (with-output-to-string (*standard-output*)  
           (let ((*print-pretty* *sldb-pprint-frames*))  
             (debug::print-frame-call frame :verbosity 1 :number t)))))  
 (defun compute-backtrace (start end)  
   "Return a list of frames starting with frame number START and  
 continuing to frame number END or, if END is nil, the last frame on the  
1204    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
1205      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (di:frame-down f)
1206            for i from start below end            for i from start below end
1207            while f            while f
1208            collect f)))            collect f)))
1210  (defmethod backtrace (start end)  (defimplementation print-frame (frame stream)
1211    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (let ((*standard-output* stream))
1212        (debug::print-frame-call frame :verbosity 1 :number nil)))
 (defmethod debugger-info-for-emacs (start end)  
   (list (format-condition-for-emacs)  
         (backtrace start end)))  
1214  (defmethod frame-source-location-for-emacs (index)  (defimplementation frame-source-location-for-emacs (index)
1215    (code-location-source-location (di:frame-code-location (nth-frame index))))    (code-location-source-location (di:frame-code-location (nth-frame index))))
1217  (defmethod eval-in-frame (form index)  (defimplementation eval-in-frame (form index)
1218    (di:eval-in-frame (nth-frame index) form))    (di:eval-in-frame (nth-frame index) form))
1220  (defslimefun pprint-eval-string-in-frame (string index)  (defimplementation frame-locals (index)
     (di:eval-in-frame (nth-frame index) (from-string string)))))  
 (defslimefun inspect-in-frame (string index)  
   (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))  
 (defmethod frame-locals (index)  
1221    (let* ((frame (nth-frame index))    (let* ((frame (nth-frame index))
1222           (location (di:frame-code-location frame))           (location (di:frame-code-location frame))
1223           (debug-function (di:frame-debug-function frame))           (debug-function (di:frame-debug-function frame))
1224           (debug-variables (di::debug-function-debug-variables debug-function)))           (debug-variables (di::debug-function-debug-variables debug-function)))
1225      (loop for v across debug-variables      (loop for v across debug-variables collect
1226            collect (list            (list :name (di:debug-variable-symbol v)
1227                     :symbol (di:debug-variable-symbol v)                  :id (di:debug-variable-id v)
1228                     :id (di:debug-variable-id v)                  :value (ecase (di:debug-variable-validity v location)
1229                     :value-string                           (:valid
1230                     (if (eq (di:debug-variable-validity v location)                            (di:debug-variable-value v frame))
1231                             :valid)                           ((:invalid :unknown)
1232                         (to-string (di:debug-variable-value v frame))                            ':not-available))))))
1233                         "<not-available>")))))  
1234    (defimplementation frame-catch-tags (index)
1235  (defmethod frame-catch-tags (index)    (mapcar #'car (di:frame-catches (nth-frame index))))
1236    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  
1237          collect `(,tag . ,(code-location-source-location code-location))))  (defun set-step-breakpoints (frame)
1238      (when (di:debug-block-elsewhere-p (di:code-location-debug-block
1239  (defslimefun invoke-nth-restart (index)                                       (di:frame-code-location frame)))
1240    (invoke-restart-interactively (nth-restart index)))      (error "Cannot step, in elsewhere code~%"))
1241      (let* ((code-location (di:frame-code-location frame))
1242             (debug::*bad-code-location-types*
1243              (remove :call-site debug::*bad-code-location-types*))
1244             (next (debug::next-code-locations code-location)))
1245        (cond (next
1246               (let ((steppoints '()))
1247                 (flet ((hook (frame breakpoint)
1248                          (let ((debug:*stack-top-hint* frame))
1249                            (mapc #'di:delete-breakpoint steppoints)
1250                            (let ((cl (di::breakpoint-what breakpoint)))
1251                              (break "Breakpoint: ~S ~S"
1252                                     (di:code-location-kind cl)
1253                                     (di::compiled-code-location-pc cl))))))
1254                   (dolist (code-location next)
1255                     (let ((bp (di:make-breakpoint #'hook code-location
1256                                                   :kind :code-location)))
1257                       (di:activate-breakpoint bp)
1258                       (push bp steppoints))))))
1259             (t
1260              (flet ((hook (frame breakpoint values cookie)
1261                       (declare (ignore cookie))
1262                       (di:delete-breakpoint breakpoint)
1263                       (let ((debug:*stack-top-hint* frame))
1264                         (break "Function-end: ~A ~A" breakpoint values))))
1265                (let* ((debug-function (di:frame-debug-function frame))
1266                       (bp (di:make-breakpoint #'hook debug-function
1267                                               :kind :function-end)))
1268                  (di:activate-breakpoint bp)))))))
1270    ;; (defslimefun sldb-step (frame)
1271    ;;   (cond ((find-restart 'continue *swank-debugger-condition*)
1272    ;;          (set-step-breakpoints (nth-frame frame))
1273    ;;          (continue *swank-debugger-condition*))
1274    ;;         (t
1275    ;;          (error "Cannot continue in from condition: ~A"
1276    ;;                 *swank-debugger-condition*))))
1278    (defun frame-cfp (frame)
1279      "Return the Control-Stack-Frame-Pointer for FRAME."
1280      (etypecase frame
1281        (di::compiled-frame (di::frame-pointer frame))
1282        ((or di::interpreted-frame null) -1)))
1284    (defun frame-ip (frame)
1285      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1286      (if (not frame)
1287          -1
1288          (let ((debug-fun (di::frame-debug-function frame)))
1289            (etypecase debug-fun
1290              (di::compiled-debug-function
1291               (let* ((code-loc (di:frame-code-location frame))
1292                      (component (di::compiled-debug-function-component debug-fun))
1293                      (pc (di::compiled-code-location-pc code-loc))
1294                      (ip (sys:without-gcing
1295                           (sys:sap-int
1296                            (sys:sap+ (kernel:code-instructions component) pc)))))
1297                 (values ip pc)))
1298              ((or di::bogus-debug-function di::interpreted-debug-function)
1299               -1)))))
1301    (defun frame-registers (frame)
1302      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1303      (let* ((cfp (frame-cfp frame))
1304             (csp (frame-cfp (di::frame-up frame)))
1305             (ip (frame-ip frame))
1306             (ocfp (frame-cfp (di::frame-down frame)))
1307             (lra (frame-ip (di::frame-down frame))))
1308        (values csp cfp ip ocfp lra)))
1310    (defun print-frame-registers (frame-number)
1311      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1312        (flet ((fixnum (p) (etypecase p
1313                             (integer p)
1314                             (sys:system-area-pointer (sys:sap-int p)))))
1315          (apply #'format t "~
1316    CSP  =  ~X
1317    CFP  =  ~X
1318    IP   =  ~X
1319    OCFP =  ~X
1320    LRA  =  ~X~%" (mapcar #'fixnum
1321                          (multiple-value-list (frame-registers frame)))))))
1324    (defimplementation disassemble-frame (frame-number)
1325      "Return a string with the disassembly of frames code."
1326      (print-frame-registers frame-number)
1327      (terpri)
1328      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1329             (debug-fun (di::frame-debug-function frame)))
1330        (etypecase debug-fun
1331          (di::compiled-debug-function
1332           (let* ((component (di::compiled-debug-function-component debug-fun))
1333                  (fun (di:debug-function-function debug-fun)))
1334             (if fun
1335                 (disassemble fun)
1336                 (disassem:disassemble-code-component component))))
1337          (di::bogus-debug-function
1338           (format t "~%[Disassembling bogus frames not implemented]")))))
1340    #+(or)
1341    (defun print-binding-stack ()
1342      (flet ((bsp- (p) (sys:sap+ p (- (* vm:binding-size vm:word-bytes))))
1343             (frob (p offset) (kernel:make-lisp-obj (sys:sap-ref-32 p offset))))
1344        (do ((bsp (bsp- (kernel:binding-stack-pointer-sap)) (bsp- bsp))
1345             (start (sys:int-sap (lisp::binding-stack-start))))
1346            ((sys:sap= bsp start))
1347          (format t "~X:  ~S = ~S~%"
1348                  (sys:sap-int bsp)
1349                  (frob bsp (* vm:binding-symbol-slot vm:word-bytes))
1350                  (frob bsp (* vm:binding-value-slot vm:word-bytes))))))
1352    ;; (print-binding-stack)
1354    #+(or)
1355    (defun print-catch-blocks ()
1356      (do ((b (di::descriptor-sap lisp::*current-catch-block*)
1357              (sys:sap-ref-sap b (* vm:catch-block-previous-catch-slot
1358                                    vm:word-bytes))))
1359          (nil)
1360        (let ((int (sys:sap-int b)))
1361          (when (zerop int) (return))
1362          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1363            (let ((uwp (ref vm:catch-block-current-uwp-slot))
1364                  (cfp (ref vm:catch-block-current-cont-slot))
1365                  (tag (ref vm:catch-block-tag-slot))
1366                  )
1367          (format t "~X:  uwp = ~8X  cfp = ~8X  tag = ~X~%"
1368                  int uwp cfp (kernel:make-lisp-obj tag)))))))
1370    ;; (print-catch-blocks)
1372    #+(or)
1373    (defun print-unwind-blocks ()
1374      (do ((b (di::descriptor-sap lisp::*current-unwind-protect-block*)
1375              (sys:sap-ref-sap b (* vm:unwind-block-current-uwp-slot
1376                                    vm:word-bytes))))
1377          (nil)
1378        (let ((int (sys:sap-int b)))
1379          (when (zerop int) (return))
1380          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1381            (let ((cfp (ref vm:unwind-block-current-cont-slot)))
1382              (format t "~X:  cfp = ~X~%" int cfp))))))
1384  (defslimefun sldb-abort ()  ;; (print-unwind-blocks)
   (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))  
1387  ;;;; Inspecting  ;;;; Inspecting
 (defvar *inspectee*)  
 (defvar *inspectee-parts*)  
 (defvar *inspector-stack* '())  
 (defvar *inspector-history* (make-array 10 :adjustable t :fill-pointer 0))  
 (defvar *inspect-length* 30)  
 (defun reset-inspector ()  
   (setq *inspectee* nil)  
   (setq *inspectee-parts* nil)  
   (setq *inspector-stack* nil)  
   (setf (fill-pointer *inspector-history*) 0))  
 (defslimefun init-inspector (string)  
   (inspect-object (eval (from-string string))))  
 (defun print-part-to-string (value)  
   (let ((*print-pretty* nil))  
     (let ((string (to-string value))  
           (pos (position value *inspector-history*)))  
       (if pos  
           (format nil "#~D=~A" pos string)  
 (defun inspect-object (object)  
   (push (setq *inspectee* object) *inspector-stack*)  
   (unless (find object *inspector-history*)  
     (vector-push-extend object *inspector-history*))  
   (multiple-value-bind (text parts) (inspected-parts object)  
     (setq *inspectee-parts* parts)  
       (list :text text  
             :type (to-string (type-of object))  
             :primitive-type (describe-primitive-type object)  
             :parts (loop for (label . value) in parts  
                          collect (cons label  
                                        (print-part-to-string value))))))  
1389  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1390    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1391      vm:function-pointer-type      vm:function-pointer-type
# Line 1168  stack." Line 1410  stack."
1410       (append (apropos-list "-TYPE" "VM" t)       (append (apropos-list "-TYPE" "VM" t)
1411               (apropos-list "-TYPE" "BIGNUM" t)))))               (apropos-list "-TYPE" "BIGNUM" t)))))
1413  (defun describe-primitive-type (object)  (defimplementation describe-primitive-type (object)
1414    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1415      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1416             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1417        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1418        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1419                                    vm:function-pointer-type                                   vm:function-pointer-type
1420                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
1421                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
1422                                    ))                                   ))
1423               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
1424                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
1425                                         :key #'symbol-value)))                                    :key #'symbol-value)))
1426                 (format t ", type: ~A]" type-symbol)))            (format t ", type: ~A" type-symbol))))))
             (t (format t "]"))))))  
 (defun nth-part (index)  
   (cdr (nth index *inspectee-parts*)))  
 (defslimefun inspect-nth-part (index)  
   (inspect-object (nth-part index)))  
 (defslimefun inspector-pop ()  
   "Drop the inspector stack and inspect the second element.  Return  
 nil if there's no second element."  
   (cond ((cdr *inspector-stack*)  
          (pop *inspector-stack*)  
          (inspect-object (pop *inspector-stack*)))  
         (t nil)))  
 (defslimefun inspector-next ()  
   "Inspect the next element in the *inspector-history*."  
   (let ((position (position *inspectee* *inspector-history*)))  
     (cond ((= (1+ position) (length *inspector-history*))  
           (t (inspect-object (aref *inspector-history* (1+ position)))))))  
 (defslimefun quit-inspector ()  
 (defslimefun describe-inspectee ()  
   "Describe the currently inspected object."  
   (print-description-to-string *inspectee*))  
 (defgeneric inspected-parts (object)  
    "Return a short description and a list of (label . value) pairs."))  
1428  (defmethod inspected-parts (o)  (defimplementation inspected-parts (o)
1429    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
1430           (inspected-parts-of-value-cell o))           (inspected-parts-of-value-cell o))
1431          (t          (t
# Line 1235  nil if there's no second element." Line 1443  nil if there's no second element."
1443    (values (format nil "~A~% is a value cell." o)    (values (format nil "~A~% is a value cell." o)
1444            (list (cons "Value" (c:value-cell-ref o)))))            (list (cons "Value" (c:value-cell-ref o)))))
 ;; borrowed from sbcl  
 (defmethod inspected-parts ((object cons))  
   (if (consp (cdr object))  
       (inspected-parts-of-nontrivial-list object)  
       (inspected-parts-of-simple-cons object)))  
 (defun inspected-parts-of-simple-cons (object)  
   (values "The object is a CONS."  
           (list (cons (string 'car) (car object))  
                 (cons (string 'cdr) (cdr object)))))  
 (defun inspected-parts-of-nontrivial-list (object)  
   (let ((length 0)  
         (in-list object)  
         (reversed-elements nil))  
     (flet ((done (description-format)  
              (return-from inspected-parts-of-nontrivial-list  
                (values (format nil description-format length)  
                        (nreverse reversed-elements)))))  
        (cond ((null in-list)  
               (done "The object is a proper list of length ~S.~%"))  
              ((>= length *inspect-length*)  
               (push (cons  (string 'rest) in-list) reversed-elements)  
               (done "The object is a long list (more than ~S elements).~%"))  
              ((consp in-list)  
               (push (cons (format nil "~D" length) (pop in-list))  
               (incf length))  
               (push (cons (string 'rest) in-list) reversed-elements)  
               (done "The object is an improper list of length ~S.~%")))))))  
1446  (defmethod inspected-parts ((o function))  (defmethod inspected-parts ((o function))
1447    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
1448      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
# Line 1304  nil if there's no second element." Line 1479  nil if there's no second element."
1479            `(("Name" . ,(kernel:fdefn-name o))            `(("Name" . ,(kernel:fdefn-name o))
1480              ("Function" . ,(kernel:fdefn-function o)))))              ("Function" . ,(kernel:fdefn-function o)))))
1482  ;;; Local Variables:  
1483  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))  ;;;; Profiling
1484  ;;; End:  (defimplementation profile (fname)
1485      (eval `(profile:profile ,fname)))
1487    (defimplementation unprofile (fname)
1488      (eval `(profile:unprofile ,fname)))
1490    (defimplementation unprofile-all ()
1491      (eval '(profile:unprofile))
1492      "All functions unprofiled.")
1494    (defimplementation profile-report ()
1495      (eval '(profile:report-time)))
1497    (defimplementation profile-reset ()
1498      (eval '(profile:reset-time))
1499      "Reset profiling counters.")
1501    (defimplementation profiled-functions ()
1502      profile:*timed-functions*)
1504    (defimplementation profile-package (package callers methods)
1505      (profile:profile-all :package package
1506                           :callers-p callers
1507                           :methods methods))
1510    ;;;; Multiprocessing
1512    #+mp
1513    (progn
1514      (defimplementation startup-multiprocessing ()
1515        ;; Threads magic: this never returns! But top-level becomes
1516        ;; available again.
1517        (mp::startup-idle-and-top-level-loops))
1519      (defimplementation spawn (fn &key (name "Anonymous"))
1520        (mp:make-process fn :name name))
1522      (defimplementation thread-name (thread)
1523        (mp:process-name thread))
1525      (defimplementation thread-status (thread)
1526        (mp:process-whostate thread))
1528      (defimplementation current-thread ()
1529        mp:*current-process*)
1531      (defimplementation all-threads ()
1532        (copy-list mp:*all-processes*))
1534      (defimplementation interrupt-thread (thread fn)
1535        (mp:process-interrupt thread fn))
1537      (defimplementation kill-thread (thread)
1538        (mp:destroy-process thread))
1540      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
1542      (defstruct (mailbox (:conc-name mailbox.))
1543        (mutex (mp:make-lock "process mailbox"))
1544        (queue '() :type list))
1546      (defun mailbox (thread)
1547        "Return THREAD's mailbox."
1548        (mp:with-lock-held (*mailbox-lock*)
1549          (or (getf (mp:process-property-list thread) 'mailbox)
1550              (setf (getf (mp:process-property-list thread) 'mailbox)
1551                    (make-mailbox)))))
1553      (defimplementation send (thread message)
1554        (let* ((mbox (mailbox thread))
1555               (mutex (mailbox.mutex mbox)))
1556          (mp:with-lock-held (mutex)
1557            (setf (mailbox.queue mbox)
1558                  (nconc (mailbox.queue mbox) (list message))))))
1560      (defimplementation receive ()
1561        (let* ((mbox (mailbox mp:*current-process*))
1562               (mutex (mailbox.mutex mbox)))
1563          (mp:process-wait "receive" #'mailbox.queue mbox)
1564          (mp:with-lock-held (mutex)
1565            (pop (mailbox.queue mbox)))))
1567      )
1569    (defimplementation quit-lisp ()
1570      (ext::quit))

Removed from v.1.32  
changed lines
  Added in v.1.99

  ViewVC Help
Powered by ViewVC 1.1.5