/[slime]/slime/swank-cmucl.lisp
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.71 by heller, Wed Feb 25 20:51:50 2004 UTC
# Line 1  Line 1 
1  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
2    
3  (declaim (optimize debug))  (declaim (optimize (debug 2)))
4    
5  (in-package :swank)  (in-package :swank)
6    
7  ;; Turn on xref. [should we?]  (in-package :lisp)
 (setf c:*record-xref-info* t)  
8    
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)))
15    
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               (bytes-read (system:read-n-bytes stream s start numbytes t)))
28          (if (< bytes-read numbytes)
29              (+ start bytes-read)
30              end)))
31    
32      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
33        (when s
34          (setf (symbol-value s) t)))
35    
36      )
37    
38    (in-package :swank)
39    
40    
41    ;;;; TCP server.
42    
43    (setq *swank-in-background* :sigio)
44    
45    (defimplementation create-socket (host port)
46      (ext:create-inet-listener port :stream
47                                :reuse-address t
48                                :host (resolve-hostname host)))
49    
50    (defimplementation local-port (socket)
51      (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
52    
53    (defimplementation close-socket (socket)
54      (ext:close-socket (socket-fd socket)))
55    
56    (defimplementation accept-connection (socket)
57      #+MP (mp:process-wait-until-fd-usable socket :input)
58      (make-socket-io-stream (ext:accept-tcp-connection socket)))
59    
60    (defvar *sigio-handlers* '()
61      "List of (key . (fn . args)) pairs to be called on SIGIO.")
62    
63    (defun sigio-handler (signal code scp)
64      (declare (ignore signal code scp))
65      (mapc (lambda (handler) (funcall (cdr handler))) *sigio-handlers*))
66    
67    (defun set-sigio-handler ()
68      (sys:enable-interrupt unix:SIGIO (lambda (signal code scp)
69                                         (sigio-handler signal code scp))))
70    
71    (defun fcntl (fd command arg)
72      (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
73        (cond (ok)
74              (t (error "fcntl: ~A" (unix:get-unix-error-msg error))))))
75    
76    (defimplementation add-sigio-handler (socket fn)
77      (set-sigio-handler)
78      (let ((fd (socket-fd socket)))
79        (format *debug-io* "; Adding input handler: ~S ~%" fd)
80        (fcntl fd unix:f-setown (unix:unix-getpid))
81        (fcntl fd unix:f-setfl unix:FASYNC)
82        (push (cons fd fn) *sigio-handlers*)))
83    
84    (defimplementation remove-sigio-handlers (socket)
85      (let ((fd (socket-fd socket)))
86        (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car))
87        (sys:invalidate-descriptor fd))
88      (close socket))
89    
90    (defimplementation add-fd-handler (socket fn)
91      (let ((fd (socket-fd socket)))
92        (format *debug-io* "; Adding fd handler: ~S ~%" fd)
93        (sys:add-fd-handler fd :input (lambda (_)
94                                        _
95                                        (funcall fn)))))
96    
97    (defimplementation remove-fd-handlers (socket)
98      (sys:invalidate-descriptor (socket-fd socket)))
99    
100    (defimplementation make-fn-streams (input-fn output-fn)
101      (let* ((output (make-slime-output-stream output-fn))
102             (input  (make-slime-input-stream input-fn output)))
103        (values input output)))
104    
105    ;;;;; Socket helpers.
106    
107    (defun socket-fd (socket)
108      "Return the filedescriptor for the socket represented by SOCKET."
109      (etypecase socket
110        (fixnum socket)
111        (sys:fd-stream (sys:fd-stream-fd socket))))
112    
113    (defun resolve-hostname (hostname)
114      "Return the IP address of HOSTNAME as an integer."
115      (let* ((hostent (ext:lookup-host-entry hostname))
116             (address (car (ext:host-entry-addr-list hostent))))
117        (ext:htonl address)))
118    
119    (defun make-socket-io-stream (fd)
120      "Create a new input/output fd-stream for FD."
121      (sys:make-fd-stream fd :input t :output t :element-type 'base-char))
122    
123  (defun set-fd-non-blocking (fd)  (defun set-fd-non-blocking (fd)
124    (flet ((fcntl (fd cmd arg)    (flet ((fcntl (fd cmd arg)
125             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)
126               (or flags               (or flags
127                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))
128      (let ((flags (fcntl fd unix:F-GETFL 0)))      (let ((flags (fcntl fd unix:F-GETFL 0)))
129        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))
130    
131    
132  ;;;; TCP server.  ;;;; Unix signals
133    
134  (defun resolve-hostname (name)  (defmethod call-without-interrupts (fn)
135    (let* ((hostent (ext:lookup-host-entry name))    (sys:without-interrupts (funcall fn)))
          (address (car (ext:host-entry-addr-list hostent))))  
     (ext:htonl address)))  
136    
137  (defun create-swank-server (port &key (reuse-address t)  (defimplementation getpid ()
138                              (address "localhost"))    (unix:unix-getpid))
139    "Create a SWANK TCP server."  
140    (let* ((ip (resolve-hostname address))  (defimplementation lisp-implementation-type-name ()
141           (fd (ext:create-inet-listener port :stream    "cmucl")
                                        :reuse-address reuse-address  
                                        :host ip)))  
     (system:add-fd-handler fd :input #'accept-connection)  
     (nth-value 1 (ext::get-socket-host-and-port fd))))  
   
 (defun accept-connection (socket)  
   "Accept one Swank TCP connection on SOCKET and then close it."  
   (setup-request-handler (ext:accept-tcp-connection socket))  
   (sys:invalidate-descriptor socket)  
   (unix:unix-close socket))  
   
 (defun open-stream-to-emacs ()  
   "Return an output-stream to Emacs' output buffer."  
   (let* ((ip (resolve-hostname "localhost"))  
          (listener (ext:create-inet-listener 0 :stream :host ip))  
          (port (nth-value 1 (ext::get-socket-host-and-port listener))))  
     (unwind-protect  
          (progn  
            (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))  
                      (make-slime-output-stream)))  
          (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*)))))  
   (sys:scrub-control-stack))  
142    
143    
144  ;;;; Stream handling  ;;;; Stream handling
145    
146  (defstruct (slime-output-stream  (defstruct (slime-output-stream
147               (:include lisp::lisp-stream               (:include lisp::lisp-stream
148                         (lisp::misc #'sos/misc)                         (lisp::misc #'sos/misc)
149                         (lisp::out #'sos/out)                         (lisp::out #'sos/out)
150                         (lisp::sout #'sos/sout))                         (lisp::sout #'sos/sout))
151               (:conc-name sos.)               (:conc-name sos.)
152               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
153                 (:constructor make-slime-output-stream (output-fn)))
154      (output-fn nil :type function)
155    (buffer (make-string 512) :type string)    (buffer (make-string 512) :type string)
156    (index 0 :type kernel:index)    (index 0 :type kernel:index)
157    (column 0 :type kernel:index))    (column 0 :type kernel:index))
# Line 117  The request is read from the socket as a Line 175  The request is read from the socket as a
175  (defun sos/sout (stream string start end)  (defun sos/sout (stream string start end)
176    (loop for i from start below end    (loop for i from start below end
177          do (sos/out stream (aref string i))))          do (sos/out stream (aref string i))))
178    
179  (defun sos/misc (stream operation &optional arg1 arg2)  (defun sos/misc (stream operation &optional arg1 arg2)
180    (declare (ignore arg1 arg2))    (declare (ignore arg1 arg2))
181    (case operation    (case operation
182      ((:force-output :finish-output)      ((:force-output :finish-output)
183       (let ((end (sos.index stream)))       (let ((end (sos.index stream)))
184         (unless (zerop end)         (unless (zerop end)
185           (send-to-emacs `(:read-output ,(subseq (sos.buffer stream) 0 end)))           (funcall (sos.output-fn stream) (subseq (sos.buffer stream) 0 end))
186           (setf (sos.index stream) 0))))           (setf (sos.index stream) 0))))
187      (:charpos (sos.column stream))      (:charpos (sos.column stream))
188      (:line-length 75)      (:line-length 75)
189      (:file-position nil)      (:file-position nil)
# Line 135  The request is read from the socket as a Line 193  The request is read from the socket as a
193      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
194    
195  (defstruct (slime-input-stream  (defstruct (slime-input-stream
196               (:include string-stream               (:include string-stream
197                         (lisp::in #'sis/in)                         (lisp::in #'sis/in)
198                         (lisp::misc #'sis/misc))                         (lisp::misc #'sis/misc))
199               (:conc-name sis.)               (:conc-name sis.)
200               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
201    (buffer "" :type string)               (:constructor make-slime-input-stream (input-fn sos)))
202    (index 0 :type kernel:index))    (input-fn nil :type function)
203      ;; We know our sibling output stream, so that we can force it before
204      ;; requesting input.
205      (sos      nil :type slime-output-stream)
206      (buffer   ""  :type string)
207      (index    0   :type kernel:index))
208    
209  (defun sis/in (stream eof-errorp eof-value)  (defun sis/in (stream eof-errorp eof-value)
210    (declare (ignore eof-errorp eof-value))    (declare (ignore eof-errorp eof-value))
211    (let ((index (sis.index stream))    (let ((index (sis.index stream))
212          (buffer (sis.buffer stream)))          (buffer (sis.buffer stream)))
213      (when (= index (length buffer))      (when (= index (length buffer))
214        (setf buffer (slime-read-string))        (force-output (sis.sos stream))
215          (setf buffer (funcall (sis.input-fn stream)))
216        (setf (sis.buffer stream) buffer)        (setf (sis.buffer stream) buffer)
217        (setf index 0))        (setf index 0))
218      (prog1 (aref buffer index)      (prog1 (aref buffer index)
# Line 162  The request is read from the socket as a Line 226  The request is read from the socket as a
226      (:unread (setf (aref (sis.buffer stream)      (:unread (setf (aref (sis.buffer stream)
227                           (decf (sis.index stream)))                           (decf (sis.index stream)))
228                     arg1))                     arg1))
229      (:clear-input (setf (sis.index stream) 0      (:clear-input
230         (setf (sis.index stream) 0
231                          (sis.buffer stream) ""))                          (sis.buffer stream) ""))
232      (:listen (< (sis.index stream) (length (sis.buffer stream))))      (:listen (< (sis.index stream) (length (sis.buffer stream))))
233      (:charpos nil)      (:charpos nil)
# Line 201  C:*COMPILER-NOTIFICATION-FUNCTION*. The Line 266  C:*COMPILER-NOTIFICATION-FUNCTION*. The
266  craft our own error messages, which can omit a lot of redundant  craft our own error messages, which can omit a lot of redundant
267  information."  information."
268    (unless (eq condition *previous-compiler-condition*)    (unless (eq condition *previous-compiler-condition*)
269      (let ((context (or (c::find-error-context nil) *previous-context*)))      (let ((context (c::find-error-context nil)))
270        (setq *previous-compiler-condition* condition)        (setq *previous-compiler-condition* condition)
271        (setq *previous-context* context)        (setq *previous-context* context)
272        (signal-compiler-condition condition context))))        (signal-compiler-condition condition context))))
# Line 211  information." Line 276  information."
276             'compiler-condition             'compiler-condition
277             :original-condition condition             :original-condition condition
278             :severity (severity-for-emacs condition)             :severity (severity-for-emacs condition)
279             :message (brief-compiler-message-for-emacs condition context)             :short-message (brief-compiler-message-for-emacs condition)
280               :message (long-compiler-message-for-emacs condition context)
281             :location (compiler-note-location context))))             :location (compiler-note-location context))))
282    
283  (defun severity-for-emacs (condition)  (defun severity-for-emacs (condition)
# Line 221  information." Line 287  information."
287      (c::style-warning :note)      (c::style-warning :note)
288      (c::warning :warning)))      (c::warning :warning)))
289    
290  (defun brief-compiler-message-for-emacs (condition error-context)  (defun brief-compiler-message-for-emacs (condition)
291    "Briefly describe a compiler error for Emacs.    "Briefly describe a compiler error for Emacs.
292  When Emacs presents the message it already has the source popped up  When Emacs presents the message it already has the source popped up
293  and the source form highlighted. This makes much of the information in  and the source form highlighted. This makes much of the information in
294  the error-context redundant."  the error-context redundant."
295      (princ-to-string condition))
296    
297    (defun long-compiler-message-for-emacs (condition error-context)
298      "Describe a compiler error for Emacs including context information."
299    (declare (type (or c::compiler-error-context null) error-context))    (declare (type (or c::compiler-error-context null) error-context))
300    (multiple-value-bind (enclosing source)    (multiple-value-bind (enclosing source)
301        (if error-context        (if error-context
# Line 234  the error-context redundant." Line 304  the error-context redundant."
304      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"
305              enclosing source condition)))              enclosing source condition)))
306    
   
307  (defun compiler-note-location (context)  (defun compiler-note-location (context)
308    (cond (context    (cond (context
309           (resolve-note-location           (resolve-note-location
# Line 277  the error-context redundant." Line 346  the error-context redundant."
346           (make-location (list :file (namestring *compile-file-truename*))           (make-location (list :file (namestring *compile-file-truename*))
347                          (list :position 0)))                          (list :position 0)))
348          (*compile-filename*          (*compile-filename*
349           (make-location (list :file *compile-filename*) (list :position 0)))           (make-location (list :file *compile-filename*)
350                            (list :position 0)))
351          (t          (t
352           (list :error "No error location available"))))           (list :error "No error location available"))))
353    
354  (defmacro with-compilation-hooks (() &body body)  (defimplementation call-with-compilation-hooks (function)
355    "Execute BODY and record the set of compiler notes."    (let ((*previous-compiler-condition* nil)
356    `(let ((*previous-compiler-condition* nil)          (*previous-context* nil)
357           (*previous-context* nil)          (*print-readably* nil))
          (*print-readably* nil))  
358      (handler-bind ((c::compiler-error #'handle-notification-condition)      (handler-bind ((c::compiler-error #'handle-notification-condition)
359                     (c::style-warning  #'handle-notification-condition)                     (c::style-warning  #'handle-notification-condition)
360                     (c::warning        #'handle-notification-condition))                     (c::warning        #'handle-notification-condition))
361        ,@body)))        (funcall function))))
362    
363  (defmethod compile-file-for-emacs (filename load-p)  (defimplementation compile-file-for-emacs (filename load-p)
364    (clear-xref-info filename)    (clear-xref-info filename)
365    (with-compilation-hooks ()    (with-compilation-hooks ()
366      (let ((*buffer-name* nil)      (let ((*buffer-name* nil)
367            (*compile-filename* filename))            (*compile-filename* filename))
368          (compile-file filename :load load-p))))        (multiple-value-bind (fasl-file warnings-p failure-p)
369              (compile-file filename)
370            (declare (ignore warnings-p))
371            (when (and load-p (not failure-p))
372              (load fasl-file))))))
373    
374  (defmethod compile-string-for-emacs (string &key buffer position)  (defimplementation compile-string-for-emacs (string &key buffer position)
375    (with-compilation-hooks ()    (with-compilation-hooks ()
376      (let ((*package* *buffer-package*)      (let ((*package* *buffer-package*)
377            (*compile-filename* nil)            (*compile-filename* nil)
# Line 318  the error-context redundant." Line 391  the error-context redundant."
391  (defun lookup-xrefs (finder name)  (defun lookup-xrefs (finder name)
392    (xref-results-for-emacs (funcall finder (from-string name))))    (xref-results-for-emacs (funcall finder (from-string name))))
393    
394  (defslimefun who-calls (function-name)  (defimplementation who-calls (function-name)
   "Return the places where FUNCTION-NAME is called."  
395    (lookup-xrefs #'xref:who-calls function-name))    (lookup-xrefs #'xref:who-calls function-name))
396    
397  (defslimefun who-references (variable)  (defimplementation who-references (variable)
   "Return the places where the global variable VARIABLE is referenced."  
398    (lookup-xrefs #'xref:who-references variable))    (lookup-xrefs #'xref:who-references variable))
399    
400  (defslimefun who-binds (variable)  (defimplementation who-binds (variable)
   "Return the places where the global variable VARIABLE is bound."  
401    (lookup-xrefs #'xref:who-binds variable))    (lookup-xrefs #'xref:who-binds variable))
402    
403  (defslimefun who-sets (variable)  (defimplementation who-sets (variable)
   "Return the places where the global variable VARIABLE is set."  
404    (lookup-xrefs #'xref:who-sets variable))    (lookup-xrefs #'xref:who-sets variable))
405    
406  #+cmu19  #+cmu19
407  (progn  (progn
408    (defslimefun who-macroexpands (macro)    (defimplementation who-macroexpands (macro)
     "Return the places where MACRO is expanded."  
409      (lookup-xrefs #'xref:who-macroexpands macro))      (lookup-xrefs #'xref:who-macroexpands macro))
410    
411    (defslimefun who-specializes (class)    (defimplementation who-specializes (class)
     "Return the methods with specializers for CLASS."  
412      (let* ((methods (xref::who-specializes (find-class (from-string class))))      (let* ((methods (xref::who-specializes (find-class (from-string class))))
413             (locations (mapcar #'method-source-location methods)))             (locations (mapcar #'method-source-location methods)))
414        (group-xrefs (mapcar (lambda (m l)        (group-xrefs (mapcar (lambda (m l)
415                               (cons (let ((*print-pretty* nil))                               (cons (let ((*print-pretty* nil))
416                                       (to-string m))                                       (to-string m))
417                                     l))                                     l))
418                             methods locations))))                             methods locations)))))
   )  
419    
420  (defun resolve-xref-location (xref)  (defun resolve-xref-location (xref)
421    (let ((name (xref:xref-context-name xref))    (let ((name (xref:xref-context-name xref))
# Line 380  reference   ::= (FUNCTION-SPECIFIER . SO Line 446  reference   ::= (FUNCTION-SPECIFIER . SO
446                xrefs)))                xrefs)))
447      (group-xrefs xrefs)))      (group-xrefs xrefs)))
448    
   
 (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))))  
   
449  (defun clear-xref-info (namestring)  (defun clear-xref-info (namestring)
450    "Clear XREF notes pertaining to FILENAME.    "Clear XREF notes pertaining to NAMESTRING.
451  This is a workaround for a CMUCL bug: XREF records are cumulative."  This is a workaround for a CMUCL bug: XREF records are cumulative."
452    (let ((filename (parse-namestring namestring)))    (when c:*record-xref-info*
453      (when c:*record-xref-info*      (let ((filename (truename namestring)))
454        (dolist (db (list xref::*who-calls*        (dolist (db (list xref::*who-calls*
455                          #+cmu19 xref::*who-is-called*                          #+cmu19 xref::*who-is-called*
456                          #+cmu19 xref::*who-macroexpands*                          #+cmu19 xref::*who-macroexpands*
# Line 415  This is a workaround for a CMUCL bug: XR Line 458  This is a workaround for a CMUCL bug: XR
458                          xref::*who-binds*                          xref::*who-binds*
459                          xref::*who-sets*))                          xref::*who-sets*))
460          (maphash (lambda (target contexts)          (maphash (lambda (target contexts)
461                       ;; XXX update during traversal?
462                     (setf (gethash target db)                     (setf (gethash target db)
463                           (delete-if                           (delete filename contexts
464                            (lambda (ctx)                                   :key #'xref:xref-context-file
465                              (xref-context-derived-from-p ctx filename))                                   :test #'equalp)))
                           contexts)))  
466                   db)))))                   db)))))
467    
 (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)))  
   
468  (defun unix-truename (pathname)  (defun unix-truename (pathname)
469    (ext:unix-namestring (truename pathname)))    (ext:unix-namestring (truename pathname)))
470    
# Line 529  the code omponent CODE." Line 564  the code omponent CODE."
564                         (function-source-location e)))                         (function-source-location e)))
565     :test #'equal))     :test #'equal))
566    
567  (defslimefun list-callers (symbol-name)  (defimplementation list-callers (symbol-name)
568    "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."    "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."
569    (let ((components (function-callers (from-string symbol-name)))    (let ((components (function-callers (from-string symbol-name)))
570          (xrefs '()))          (xrefs '()))
# Line 543  the code omponent CODE." Line 578  the code omponent CODE."
578          (setq xrefs (nconc defs xrefs))))          (setq xrefs (nconc defs xrefs))))
579      (group-xrefs xrefs)))      (group-xrefs xrefs)))
580    
581    (defimplementation list-callees (symbol-name)
 (defslimefun list-callees (symbol-name)  
582    (let ((fns (function-callees (from-string symbol-name))))    (let ((fns (function-callees (from-string symbol-name))))
583      (group-xrefs (mapcar (lambda (fn)      (group-xrefs (mapcar (lambda (fn)
584                             (cons (to-string (kernel:%function-name fn))                             (cons (to-string (kernel:%function-name fn))
585                                   (function-source-location fn)))                                   (function-source-location fn)))
586                           fns))))                           fns))))
587    
588    
589  ;;;; Definitions  ;;;; Definitions
590    
591  (defvar *debug-definition-finding* t  (defvar *debug-definition-finding* nil
592    "When true don't handle errors while looking for definitions.    "When true don't handle errors while looking for definitions.
593  This is useful when debugging the definition-finding code.")  This is useful when debugging the definition-finding code.")
594    
595  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
596    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY ignoring errors.  Return the source location returned
597  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
598  The second return value is the condition or nil."  return value is the condition or nil."
599    `(flet ((body () ,@body))    `(flet ((body () ,@body))
600      (if *debug-definition-finding*      (if *debug-definition-finding*
601          (body)          (body)
# Line 629  The second return value is the condition Line 664  The second return value is the condition
664             (etypecase pathname             (etypecase pathname
665               (pathname               (pathname
666                (make-location `(:file ,(guess-source-file pathname))                (make-location `(:file ,(guess-source-file pathname))
667                               `(:function-name ,(string name)))))))))))                               `(:function-name ,(string name))))
668                 (null `(:error ,(format nil "Cannot resolve: ~S" def-source)))
669                 )))))))
670    
671  (defun method-source-location (method)  (defun method-source-location (method)
672    (function-source-location (or (pcl::method-fast-function method)    (function-source-location (or (pcl::method-fast-function method)
# Line 670  The second return value is the condition Line 707  The second return value is the condition
707    (destructuring-bind (first) (function-source-locations function)    (destructuring-bind (first) (function-source-locations function)
708      first))      first))
709    
710  (defslimefun find-function-locations (symbol-name)  (defimplementation find-function-locations (symbol-name)
711    "Return a list of source-locations for SYMBOL-NAME's functions."    "Return a list of source-locations for SYMBOL-NAME's functions."
712    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)
713      (cond ((not foundp)      (cond ((not foundp)
# Line 688  The second return value is the condition Line 725  The second return value is the condition
725    
726  ;;;; Documentation.  ;;;; Documentation.
727    
728  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
729    (let ((result '()))    (let ((result '()))
730      (flet ((doc (kind)      (flet ((doc (kind)
731               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 734  The second return value is the condition Line 771  The second return value is the condition
771                         (doc nil)))                         (doc nil)))
772        result)))        result)))
773    
 (defslimefun describe-setf-function (symbol-name)  
   (print-description-to-string  
    (or (ext:info setf inverse (from-string symbol-name))  
        (ext:info setf expander (from-string symbol-name)))))  
   
 (defslimefun describe-type (symbol-name)  
   (print-description-to-string  
    (kernel:values-specifier-type (from-string symbol-name))))  
   
 (defslimefun describe-class (symbol-name)  
   (print-description-to-string (find-class (from-string symbol-name) nil)))  
   
 (defslimefun describe-alien-type (symbol-name)  
   (let ((name (from-string symbol-name)))  
     (ecase (ext:info :alien-type :kind name)  
       (:primitive  
        (print-description-to-string  
         (let ((alien::*values-type-okay* t))  
           (funcall (ext:info :alien-type :translator name) (list name)))))  
       ((:defined)  
        (print-description-to-string (ext:info :alien-type :definition name)))  
       (:unknown  
        (format nil "Unkown alien type: ~A" symbol-name)))))  
   
774  (defmacro %describe-alien (symbol-name namespace)  (defmacro %describe-alien (symbol-name namespace)
775    `(print-description-to-string    `(print-description-to-string
776      (ext:info :alien-type ,namespace (from-string ,symbol-name))))      (ext:info :alien-type ,namespace (from-string ,symbol-name))))
777    
778  (defslimefun describe-alien-struct (symbol-name)  (defimplementation describe-definition (symbol-name type)
779    (%describe-alien symbol-name :struct))    (case type
780        (:variable
781  (defslimefun describe-alien-union (symbol-name)       (describe-symbol symbol-name))
782    (%describe-alien symbol-name :union))      ((:function :generic-function)
783         (describe-function symbol-name))
784        (:setf
785         (print-description-to-string
786          (or (ext:info setf inverse (from-string symbol-name))
787              (ext:info setf expander (from-string symbol-name)))))
788        (:type
789         (print-description-to-string
790          (kernel:values-specifier-type (from-string symbol-name))))
791        (:class
792         (print-description-to-string (find-class (from-string symbol-name) nil)))
793        (:alien-type
794         (let ((name (from-string symbol-name)))
795           (ecase (ext:info :alien-type :kind name)
796             (:primitive
797              (print-description-to-string
798               (let ((alien::*values-type-okay* t))
799                 (funcall (ext:info :alien-type :translator name) (list name)))))
800             ((:defined)
801              (print-description-to-string (ext:info :alien-type
802                                                     :definition name)))
803             (:unknown
804              (format nil "Unkown alien type: ~A" symbol-name)))))
805        (:alien-struct
806         (%describe-alien symbol-name :struct))
807        (:alien-union
808         (%describe-alien symbol-name :union))
809        (:alien-enum
810         (%describe-alien symbol-name :enum))))
811    
812  (defslimefun describe-alien-enum (symbol-name)  (defimplementation arglist-string (fname)
   (%describe-alien symbol-name :enum))  
   
 (defmethod arglist-string (fname)  
813    "Return a string describing the argument list for FNAME.    "Return a string describing the argument list for FNAME.
814  The result has the format \"(...)\"."  The result has the format \"(...)\"."
815    (declare (type string fname))    (declare (type string fname))
816    (multiple-value-bind (function condition)    (multiple-value-bind (function package) (find-symbol-designator fname)
817        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))      (unless package
818      (when condition        (return-from arglist-string (format nil "(-- Unkown symbol: ~A)" fname)))
       (return-from arglist-string (format nil "(-- ~A)" condition)))  
819      (let ((arglist      (let ((arglist
820             (if (not (or (fboundp function)             (if (not (or (fboundp function)
821                          (functionp function)))                          (functionp function)))
822                 "(-- <Unknown-Function>)"                 "(-- <Unknown-Function>)"
823                 (let* ((fun (or (macro-function function)                 (let* ((fun (or (macro-function function)
824                                 (symbol-function function)))                                 (symbol-function function)))
825                        (df (di::function-debug-function fun))                        (arglist (kernel:%function-arglist
826                        (arglist (kernel:%function-arglist fun)))                                  (kernel:%function-self fun))))
827                   (cond ((eval:interpreted-function-p fun)                   (cond ((eval:interpreted-function-p fun)
828                          (eval:interpreted-function-arglist fun))                          (eval:interpreted-function-arglist fun))
829                         ((pcl::generic-function-p fun)                         ((pcl::generic-function-p fun)
830                          (pcl::gf-pretty-arglist fun))                          (pcl:generic-function-lambda-list fun))
831                         (arglist arglist)                         (arglist arglist)
832                         ;; this should work both for                         ;; this should work both for
833                         ;; compiled-debug-function and for                         ;; compiled-debug-function and for
834                         ;; interpreted-debug-function                         ;; interpreted-debug-function
835                         (df (di::debug-function-lambda-list df))                         (t (let ((df (di::function-debug-function fun)))
836                         (t "(<arglist-unavailable>)"))))))                              (if df
837        (if (stringp arglist)                                  (di::debug-function-lambda-list df)
838            arglist                                  "(<arglist-unavailable>)"))))))))
839            (to-string arglist)))))        (etypecase arglist
840            (string arglist)
841            (cons (let ((*print-case* :downcase)
842                        (*print-pretty* nil))
843                    (princ-to-string arglist)))
844            (null "()")))))
845    
846    
847  ;;;; Miscellaneous.  ;;;; Miscellaneous.
848    
849  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
850    (walker:macroexpand-all form))    (walker:macroexpand-all form))
851    
852  (defun tracedp (fname)  (in-package :c)
853    (gethash (debug::trace-fdefinition fname)  
854             debug::*traced-functions*))  (defun swank::expand-ir1-top-level (form)
855      "A scaled down version of the first pass of the compiler."
856  (defslimefun toggle-trace-fdefinition (fname-string)    (with-compilation-unit ()
857    (let ((fname (from-string fname-string)))      (let* ((*lexical-environment*
858      (cond ((tracedp fname)              (make-lexenv :default (make-null-environment)
859             (debug::untrace-1 fname)                           :cookie *default-cookie*
860             (format nil "~S is now untraced." fname))                           :interface-cookie *default-interface-cookie*))
861            (t             (*source-info* (make-lisp-source-info form))
862             (debug::trace-1 fname (debug::make-trace-info))             (*block-compile* nil)
863             (format nil "~S is now traced." fname)))))             (*block-compile-default* nil))
864          (with-ir1-namespace
865              (clear-stuff)
866            (find-source-paths form 0)
867            (ir1-top-level form '(0) t)))))
868    
869    (in-package :swank)
870    
871    (defslimefun print-ir1-converted-blocks (form)
872      (with-output-to-string (*standard-output*)
873        (c::print-all-blocks (expand-ir1-top-level (from-string form)))))
874    
875    (defslimefun print-compilation-trace (form)
876      (with-output-to-string (*standard-output*)
877        (with-input-from-string (s form)
878          (let ((*package* *buffer-package*))
879            (ext:compile-from-stream s
880                                     :verbose t
881                                     :progress t
882                                     :trace-stream *standard-output*)))))
883    
884  (defslimefun set-default-directory (directory)  (defslimefun set-default-directory (directory)
885    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
# Line 827  The result has the format \"(...)\"." Line 888  The result has the format \"(...)\"."
888    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
889    (namestring (ext:default-directory)))    (namestring (ext:default-directory)))
890    
891    ;;; source-path-{stream,file,string,etc}-position moved into
892  ;;;; 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)))))  
     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*)  
         table)))  
   
 (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))))))  
893    
894  (defun code-location-stream-position (code-location stream)  (defun code-location-stream-position (code-location stream)
895    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the
# Line 995  to find the position of the correspondin Line 956  to find the position of the correspondin
956    (safe-definition-finding    (safe-definition-finding
957     (source-location-from-code-location code-location)))     (source-location-from-code-location code-location)))
958    
 (defslimefun getpid ()  
   (unix:unix-getpid))  
   
959    
960  ;;;; Debugging  ;;;; Debugging
961    
962  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
963  (defvar *sldb-restarts*)  (defvar *sldb-restarts*)
964    
965  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
966    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
967    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
968           (*sldb-restarts* (compute-restarts *swank-debugger-condition*))           (*sldb-restarts* (compute-restarts *swank-debugger-condition*))
# Line 1028  format suitable for Emacs." Line 986  format suitable for Emacs."
986          collect (list (princ-to-string (restart-name restart))          collect (list (princ-to-string (restart-name restart))
987                        (princ-to-string restart))))                        (princ-to-string restart))))
988    
 (defun format-condition-for-emacs ()  
   (format nil "~A~%   [Condition of type ~S]"  
           (debug::safe-condition-message *swank-debugger-condition*)  
           (type-of *swank-debugger-condition*)))  
   
989  (defun nth-frame (index)  (defun nth-frame (index)
990    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (di:frame-down frame))
991         (i index (1- i)))         (i index (1- i)))
# Line 1041  format suitable for Emacs." Line 994  format suitable for Emacs."
994  (defun nth-restart (index)  (defun nth-restart (index)
995    (nth index *sldb-restarts*))    (nth index *sldb-restarts*))
996    
997  (defun format-frame-for-emacs (frame)  (defun format-frame-for-emacs (number frame)
998    (list (di:frame-number frame)    (print-with-frame-label
999          (with-output-to-string (*standard-output*)     number (lambda (*standard-output*)
1000            (let ((*print-pretty* *sldb-pprint-frames*))              (debug::print-frame-call frame :verbosity 1 :number nil))))
             (debug::print-frame-call frame :verbosity 1 :number t)))))  
1001    
1002  (defun compute-backtrace (start end)  (defun compute-backtrace (start end)
1003    "Return a list of frames starting with frame number START and    "Return a list of frames starting with frame number START and
# Line 1055  stack." Line 1007  stack."
1007      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (di:frame-down f)
1008            for i from start below end            for i from start below end
1009            while f            while f
1010            collect f)))            collect (cons i f))))
1011    
1012  (defmethod backtrace (start end)  (defimplementation backtrace (start end)
1013    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (loop for (n . frame) in (compute-backtrace start end)
1014            collect (list n (format-frame-for-emacs n frame))))
1015    
1016  (defmethod debugger-info-for-emacs (start end)  (defimplementation debugger-info-for-emacs (start end)
1017    (list (format-condition-for-emacs)    (list (debugger-condition-for-emacs)
1018          (format-restarts-for-emacs)          (format-restarts-for-emacs)
1019          (backtrace start end)))          (backtrace start end)))
1020    
1021  (defmethod frame-source-location-for-emacs (index)  (defimplementation frame-source-location-for-emacs (index)
1022    (code-location-source-location (di:frame-code-location (nth-frame index))))    (code-location-source-location (di:frame-code-location (nth-frame index))))
1023    
1024  (defmethod eval-in-frame (form index)  (defimplementation eval-in-frame (form index)
1025    (di:eval-in-frame (nth-frame index) form))    (di:eval-in-frame (nth-frame index) form))
1026    
1027  (defslimefun pprint-eval-string-in-frame (string index)  (defslimefun pprint-eval-string-in-frame (string index)
# Line 1080  stack." Line 1033  stack."
1033    (reset-inspector)    (reset-inspector)
1034    (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))    (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))
1035    
1036  (defmethod frame-locals (index)  (defimplementation frame-locals (index)
1037    (let* ((frame (nth-frame index))    (let* ((frame (nth-frame index))
1038           (location (di:frame-code-location frame))           (location (di:frame-code-location frame))
1039           (debug-function (di:frame-debug-function frame))           (debug-function (di:frame-debug-function frame))
1040           (debug-variables (di::debug-function-debug-variables debug-function)))           (debug-variables (di::debug-function-debug-variables debug-function)))
1041      (loop for v across debug-variables      (loop for v across debug-variables collect
1042            collect (list            (list :name (to-string (di:debug-variable-symbol v))
1043                     :symbol (di:debug-variable-symbol v)                  :id (di:debug-variable-id v)
1044                     :id (di:debug-variable-id v)                  :value-string (ecase (di:debug-variable-validity v location)
1045                     :value-string                                  (:valid
1046                     (if (eq (di:debug-variable-validity v location)                                   (to-string (di:debug-variable-value v frame)))
1047                             :valid)                                  ((:invalid :unknown)
1048                         (to-string (di:debug-variable-value v frame))                                   "<not-available>"))))))
                        "<not-available>")))))  
1049    
1050  (defmethod frame-catch-tags (index)  (defimplementation frame-catch-tags (index)
1051    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))
1052          collect `(,tag . ,(code-location-source-location code-location))))          collect `(,tag . ,(code-location-source-location code-location))))
1053    
# Line 1105  stack." Line 1057  stack."
1057  (defslimefun sldb-abort ()  (defslimefun sldb-abort ()
1058    (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))    (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))
1059    
1060    (defun set-step-breakpoints (frame)
1061  ;;;; Inspecting    (when (di:debug-block-elsewhere-p (di:code-location-debug-block
1062                                         (di:frame-code-location frame)))
1063        (error "Cannot step, in elsewhere code~%"))
1064      (let* ((code-location (di:frame-code-location frame))
1065             (debug::*bad-code-location-types*
1066              (remove :call-site debug::*bad-code-location-types*))
1067             (next (debug::next-code-locations code-location)))
1068        (cond (next
1069               (let ((steppoints '()))
1070                 (flet ((hook (frame breakpoint)
1071                          (let ((debug:*stack-top-hint* frame))
1072                            (mapc #'di:delete-breakpoint steppoints)
1073                            (let ((cl (di::breakpoint-what breakpoint)))
1074                              (break "Breakpoint: ~S ~S"
1075                                     (di:code-location-kind cl)
1076                                     (di::compiled-code-location-pc cl))))))
1077                   (dolist (code-location next)
1078                     (let ((bp (di:make-breakpoint #'hook code-location
1079                                                   :kind :code-location)))
1080                       (di:activate-breakpoint bp)
1081                       (push bp steppoints))))))
1082             (t
1083              (flet ((hook (frame breakpoint values cookie)
1084                       (declare (ignore cookie))
1085                       (di:delete-breakpoint breakpoint)
1086                       (let ((debug:*stack-top-hint* frame))
1087                         (break "Function-end: ~A ~A" breakpoint values))))
1088                (let* ((debug-function (di:frame-debug-function frame))
1089                       (bp (di:make-breakpoint #'hook debug-function
1090                                               :kind :function-end)))
1091                  (di:activate-breakpoint bp)))))))
1092    
1093    (defslimefun sldb-step (frame)
1094      (cond ((find-restart 'continue *swank-debugger-condition*)
1095             (set-step-breakpoints (nth-frame frame))
1096             (continue *swank-debugger-condition*))
1097            (t
1098             (error "Cannot continue in from condition: ~A"
1099                    *swank-debugger-condition*))))
1100    
1101  (defvar *inspectee*)  (defun frame-cfp (frame)
1102  (defvar *inspectee-parts*)    "Return the Control-Stack-Frame-Pointer for FRAME."
1103  (defvar *inspector-stack* '())    (etypecase frame
1104  (defvar *inspector-history* (make-array 10 :adjustable t :fill-pointer 0))      (di::compiled-frame (di::frame-pointer frame))
1105  (defvar *inspect-length* 30)      ((or di::interpreted-frame null) -1)))
1106    
1107  (defun reset-inspector ()  (defun frame-ip (frame)
1108    (setq *inspectee* nil)    "Return the (absolute) instruction pointer and the relative pc of FRAME."
1109    (setq *inspectee-parts* nil)    (if (not frame)
1110    (setq *inspector-stack* nil)        -1
1111    (setf (fill-pointer *inspector-history*) 0))        (let ((debug-fun (di::frame-debug-function frame)))
1112            (etypecase debug-fun
1113              (di::compiled-debug-function
1114               (let* ((code-loc (di:frame-code-location frame))
1115                      (component (di::compiled-debug-function-component debug-fun))
1116                      (pc (di::compiled-code-location-pc code-loc))
1117                      (ip (sys:without-gcing
1118                           (sys:sap-int
1119                            (sys:sap+ (kernel:code-instructions component) pc)))))
1120                 (values ip pc)))
1121              ((or di::bogus-debug-function di::interpreted-debug-function)
1122               -1)))))
1123    
1124    (defun frame-registers (frame)
1125      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1126      (let* ((cfp (frame-cfp frame))
1127             (csp (frame-cfp (di::frame-up frame)))
1128             (ip (frame-ip frame))
1129             (ocfp (frame-cfp (di::frame-down frame)))
1130             (lra (frame-ip (di::frame-down frame))))
1131        (values csp cfp ip ocfp lra)))
1132    
1133    (defun print-frame-registers (frame-number)
1134      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1135        (flet ((fixnum (p) (etypecase p
1136                             (integer p)
1137                             (sys:system-area-pointer (sys:sap-int p)))))
1138          (apply #'format t "~
1139    CSP  =  ~X
1140    CFP  =  ~X
1141    IP   =  ~X
1142    OCFP =  ~X
1143    LRA  =  ~X~%" (mapcar #'fixnum
1144                          (multiple-value-list (frame-registers frame)))))))
1145    
1146    (defslimefun sldb-disassemble (frame-number)
1147      "Return a string with the disassembly of frames code."
1148        (with-output-to-string (*standard-output*)
1149          (print-frame-registers frame-number)
1150          (terpri)
1151          (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1152                 (debug-fun (di::frame-debug-function frame)))
1153            (etypecase debug-fun
1154              (di::compiled-debug-function
1155               (let* ((component (di::compiled-debug-function-component debug-fun))
1156                      (fun (di:debug-function-function debug-fun)))
1157                 (if fun
1158                     (disassemble fun)
1159                     (disassem:disassemble-code-component component))))
1160              (di::bogus-debug-function
1161               (format t "~%[Disassembling bogus frames not implemented]"))))))
1162    
1163    #+(or)
1164    (defun print-binding-stack ()
1165      (flet ((bsp- (p) (sys:sap+ p (- (* vm:binding-size vm:word-bytes))))
1166             (frob (p offset) (kernel:make-lisp-obj (sys:sap-ref-32 p offset))))
1167        (do ((bsp (bsp- (kernel:binding-stack-pointer-sap)) (bsp- bsp))
1168             (start (sys:int-sap (lisp::binding-stack-start))))
1169            ((sys:sap= bsp start))
1170          (format t "~X:  ~S = ~S~%"
1171                  (sys:sap-int bsp)
1172                  (frob bsp (* vm:binding-symbol-slot vm:word-bytes))
1173                  (frob bsp (* vm:binding-value-slot vm:word-bytes))))))
1174    
1175    ;; (print-binding-stack)
1176    
1177    #+(or)
1178    (defun print-catch-blocks ()
1179      (do ((b (di::descriptor-sap lisp::*current-catch-block*)
1180              (sys:sap-ref-sap b (* vm:catch-block-previous-catch-slot
1181                                    vm:word-bytes))))
1182          (nil)
1183        (let ((int (sys:sap-int b)))
1184          (when (zerop int) (return))
1185          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1186            (let ((uwp (ref vm:catch-block-current-uwp-slot))
1187                  (cfp (ref vm:catch-block-current-cont-slot))
1188                  (tag (ref vm:catch-block-tag-slot))
1189                  )
1190          (format t "~X:  uwp = ~8X  cfp = ~8X  tag = ~X~%"
1191                  int uwp cfp (kernel:make-lisp-obj tag)))))))
1192    
1193    ;; (print-catch-blocks)
1194    
1195    #+(or)
1196    (defun print-unwind-blocks ()
1197      (do ((b (di::descriptor-sap lisp::*current-unwind-protect-block*)
1198              (sys:sap-ref-sap b (* vm:unwind-block-current-uwp-slot
1199                                    vm:word-bytes))))
1200          (nil)
1201        (let ((int (sys:sap-int b)))
1202          (when (zerop int) (return))
1203          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1204            (let ((cfp (ref vm:unwind-block-current-cont-slot)))
1205              (format t "~X:  cfp = ~X~%" int cfp))))))
1206    
1207  (defslimefun init-inspector (string)  ;; (print-unwind-blocks)
1208    (reset-inspector)  
1209    (inspect-object (eval (from-string string))))  
1210    ;;;; Inspecting
1211    
 (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)  
           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))))))  
1212  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1213    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1214      vm:function-pointer-type      vm:function-pointer-type
# Line 1168  stack." Line 1233  stack."
1233       (append (apropos-list "-TYPE" "VM" t)       (append (apropos-list "-TYPE" "VM" t)
1234               (apropos-list "-TYPE" "BIGNUM" t)))))               (apropos-list "-TYPE" "BIGNUM" t)))))
1235    
1236  (defun describe-primitive-type (object)  
1237    (defimplementation describe-primitive-type (object)
1238    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1239      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1240             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
# Line 1184  stack." Line 1250  stack."
1250                 (format t ", type: ~A]" type-symbol)))                 (format t ", type: ~A]" type-symbol)))
1251              (t (format t "]"))))))              (t (format t "]"))))))
1252    
1253  (defun nth-part (index)  (defimplementation inspected-parts (o)
   (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*))  
            nil)  
           (t (inspect-object (aref *inspector-history* (1+ position)))))))  
   
 (defslimefun quit-inspector ()  
   (reset-inspector)  
   nil)  
   
 (defslimefun describe-inspectee ()  
   "Describe the currently inspected object."  
   (print-description-to-string *inspectee*))  
   
 (defgeneric inspected-parts (object)  
   (:documentation  
    "Return a short description and a list of (label . value) pairs."))  
   
 (defmethod inspected-parts (o)  
1254    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
1255           (inspected-parts-of-value-cell o))           (inspected-parts-of-value-cell o))
1256          (t          (t
# Line 1235  nil if there's no second element." Line 1268  nil if there's no second element."
1268    (values (format nil "~A~% is a value cell." o)    (values (format nil "~A~% is a value cell." o)
1269            (list (cons "Value" (c:value-cell-ref o)))))            (list (cons "Value" (c:value-cell-ref o)))))
1270    
 ;; 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)))))  
       (loop  
        (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))  
                     reversed-elements)  
               (incf length))  
              (t  
               (push (cons (string 'rest) in-list) reversed-elements)  
               (done "The object is an improper list of length ~S.~%")))))))  
   
1271  (defmethod inspected-parts ((o function))  (defmethod inspected-parts ((o function))
1272    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
1273      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
# Line 1304  nil if there's no second element." Line 1304  nil if there's no second element."
1304            `(("Name" . ,(kernel:fdefn-name o))            `(("Name" . ,(kernel:fdefn-name o))
1305              ("Function" . ,(kernel:fdefn-function o)))))              ("Function" . ,(kernel:fdefn-function o)))))
1306    
1307    
1308    ;;;; Profiling
1309    (defimplementation profile (fname)
1310      (eval `(profile:profile ,fname)))
1311    
1312    (defimplementation unprofile (fname)
1313      (eval `(profile:unprofile ,fname)))
1314    
1315    (defimplementation unprofile-all ()
1316      (profile:unprofile)
1317      "All functions unprofiled.")
1318    
1319    (defimplementation profile-report ()
1320      (profile:report-time))
1321    
1322    (defimplementation profile-reset ()
1323      (profile:reset-time)
1324      "Reset profiling counters.")
1325    
1326    (defimplementation profiled-functions ()
1327      profile:*timed-functions*)
1328    
1329    (defimplementation profile-package (package callers methods)
1330      (profile:profile-all :package package
1331                           :callers-p callers
1332                           :methods methods))
1333    
1334    
1335    ;;;; Multiprocessing
1336    
1337    #+MP
1338    (progn
1339      (defimplementation startup-multiprocessing ()
1340        (setq *swank-in-background* :spawn)
1341        ;; Threads magic: this never returns! But top-level becomes
1342        ;; available again.
1343        (mp::startup-idle-and-top-level-loops))
1344    
1345      (defimplementation spawn (fn &key (name "Anonymous"))
1346        (mp:make-process fn :name name))
1347    
1348      (defimplementation thread-name (thread)
1349        (mp:process-name thread))
1350    
1351      (defimplementation thread-status (thread)
1352        (mp:process-whostate thread))
1353    
1354      (defimplementation current-thread ()
1355        mp:*current-process*)
1356    
1357      (defimplementation all-threads ()
1358        (copy-list mp:*all-processes*))
1359    
1360      (defimplementation interrupt-thread (thread fn)
1361        (mp:process-interrupt thread fn))
1362    
1363      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
1364    
1365      (defstruct (mailbox (:conc-name mailbox.))
1366        (mutex (mp:make-lock "process mailbox"))
1367        (queue '() :type list))
1368    
1369      (defun mailbox (thread)
1370        "Return THREAD's mailbox."
1371        (mp:with-lock-held (*mailbox-lock*)
1372          (or (getf (mp:process-property-list thread) 'mailbox)
1373              (setf (getf (mp:process-property-list thread) 'mailbox)
1374                    (make-mailbox)))))
1375    
1376      (defimplementation send (thread message)
1377        (let* ((mbox (mailbox thread))
1378               (mutex (mailbox.mutex mbox)))
1379          (mp:with-lock-held (mutex)
1380            (setf (mailbox.queue mbox)
1381                  (nconc (mailbox.queue mbox) (list message))))))
1382    
1383      (defimplementation receive ()
1384        (let* ((mbox (mailbox mp:*current-process*))
1385               (mutex (mailbox.mutex mbox)))
1386          (mp:process-wait "receive" #'mailbox.queue mbox)
1387          (mp:with-lock-held (mutex)
1388            (pop (mailbox.queue mbox)))))
1389    
1390      )
1391    
1392    
1393    ;;;; Epilogue
1394  ;;; Local Variables:  ;;; Local Variables:
1395  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))
1396  ;;; End:  ;;; End:

Legend:
Removed from v.1.32  
changed lines
  Added in v.1.71

  ViewVC Help
Powered by ViewVC 1.1.5