/[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.84 by heller, Wed Mar 10 09:10:33 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-backend)
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               (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))
38    
39      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
40        (when s
41          (setf (symbol-value s) t)))
42    
43      )
44    
45    (in-package :swank-backend)
46    
47    
48    ;;;; TCP server.
49    
50    (defimplementation preferred-communication-style ()
51      :sigio)
52    
53    (defimplementation create-socket (host port)
54      (ext:create-inet-listener port :stream
55                                :reuse-address t
56                                :host (resolve-hostname host)))
57    
58    (defimplementation local-port (socket)
59      (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
60    
61    (defimplementation close-socket (socket)
62      (ext:close-socket (socket-fd socket)))
63    
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)))
67    
68    (defvar *sigio-handlers* '()
69      "List of (key . (fn . args)) pairs to be called on SIGIO.")
70    
71    (defun sigio-handler (signal code scp)
72      (declare (ignore signal code scp))
73      (mapc (lambda (handler) (funcall (cdr handler))) *sigio-handlers*))
74    
75    (defun set-sigio-handler ()
76      (sys:enable-interrupt unix:SIGIO (lambda (signal code scp)
77                                         (sigio-handler signal code scp))))
78    
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))))))
83    
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*)))
91    
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))
97    
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)))))
104    
105    (defimplementation remove-fd-handlers (socket)
106      (sys:invalidate-descriptor (socket-fd socket)))
107    
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)))
112    
113    ;;;;; Socket helpers.
114    
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))))
120    
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))))
125        (ext:htonl address)))
126    
127    (defun make-socket-io-stream (fd)
128      "Create a new input/output fd-stream for FD."
129      (sys:make-fd-stream fd :input t :output t :element-type 'base-char))
130    
131  (defun set-fd-non-blocking (fd)  (defun set-fd-non-blocking (fd)
132    (flet ((fcntl (fd cmd arg)    (flet ((fcntl (fd cmd arg)
133             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)
134               (or flags               (or flags
135                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))
136      (let ((flags (fcntl fd unix:F-GETFL 0)))      (let ((flags (fcntl fd unix:F-GETFL 0)))
137        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))
138    
139    
140  ;;;; TCP server.  ;;;; Unix signals
141    
142  (defun resolve-hostname (name)  (defmethod call-without-interrupts (fn)
143    (let* ((hostent (ext:lookup-host-entry name))    (sys:without-interrupts (funcall fn)))
          (address (car (ext:host-entry-addr-list hostent))))  
     (ext:htonl address)))  
144    
145  (defun create-swank-server (port &key (reuse-address t)  (defimplementation getpid ()
146                              (address "localhost"))    (unix:unix-getpid))
147    "Create a SWANK TCP server."  
148    (let* ((ip (resolve-hostname address))  (defimplementation lisp-implementation-type-name ()
149           (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))  
150    
151    
152  ;;;; Stream handling  ;;;; Stream handling
153    
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))))
186    
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))))
202    
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))
216    
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
247    
248  ;;;; Compilation Commands  ;;;; Compilation Commands
249    
 (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.")
252    
253  (defvar *previous-context* nil  (defvar *previous-context* nil
254    "Previous compiler error context.")    "Previous compiler error context.")
255    
 (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)  
259    
260    
261  ;;;;; Trapping notes  ;;;;; Trapping notes
# Line 201  C:*COMPILER-NOTIFICATION-FUNCTION*. The Line 267  C:*COMPILER-NOTIFICATION-FUNCTION*. The
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))))
283    
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)))
290    
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))
297    
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)))
307    
   
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))
         (*compile-filename*  
          (make-location (list :file *compile-filename*) (list :position 0)))  
         (t  
          (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))))
353    
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))))  
359    
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."
372    
373  ;;;; XREF  ;;;; XREF
374    
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))  
383    
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)))
   (defslimefun who-specializes (class)  
     "Return the methods with specializers for CLASS."  
     (let* ((methods (xref::who-specializes (find-class (from-string class))))  
390             (locations (mapcar #'method-source-location methods)))             (locations (mapcar #'method-source-location methods)))
391        (group-xrefs (mapcar (lambda (m l)        (mapcar #'list methods locations))))
392                               (cons (let ((*print-pretty* nil))  
393                                       (to-string m))  (defun xref-results (contexts)
394                                     l))    (mapcar (lambda (xref)
395                             methods locations))))              (list (xref:xref-context-name xref)
396    )                    (resolve-xref-location xref)))
397              contexts))
398    
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 366  the error-context redundant." Line 411  the error-context redundant."
411             `(:error ,(format nil "Unkown source location: ~S ~S ~S "             `(:error ,(format nil "Unkown source location: ~S ~S ~S "
412                               name file source-path))))))                               name file source-path))))))
413    
   
 (defun xref-results-for-emacs (contexts)  
   "Prepare a list of xref contexts for Emacs.  
 The result is a list of xrefs:  
 group       ::= (FILENAME . ({reference}+))  
 reference   ::= (FUNCTION-SPECIFIER . SOURCE-LOCATION)"  
   (let ((xrefs '()))  
     (dolist (cxt contexts)  
       (let ((name (xref:xref-context-name cxt)))  
         (push (cons (to-string name)  
                     (resolve-xref-location cxt))  
               xrefs)))  
     (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)))
                           contexts)))  
431                   db)))))                   db)))))
432    
 (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)))
435    
# 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))
502    
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)))))))))  
519    
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-source-location e)))
529     :test #'equal))     :test #'equal))
530    
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))
   
544    
545  (defslimefun list-callees (symbol-name)  (defimplementation list-callees (symbol)
546    (let ((fns (function-callees (from-string symbol-name))))    (let ((fns (function-callees symbol)))
547      (group-xrefs (mapcar (lambda (fn)      (mapcar (lambda (fn)
548                             (cons (to-string (kernel:%function-name fn))                (list (kernel:%function-name fn)
549                                   (function-source-location fn)))                      (function-source-location fn)))
550                           fns))))              fns)))
551    
552    
553  ;;;; Definitions  ;;;; Definitions
554    
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.")
558    
559  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
560    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY ignoring errors.  Return the source location returned
561  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
562  The second return value is the condition or nil."  return value is the condition or nil."
563    `(flet ((body () ,@body))    `(flet ((body () ,@body))
564      (if *debug-definition-finding*      (if *debug-definition-finding*
565          (body)          (body)
# Line 580  The second return value is the condition Line 579  The second return value is the condition
579             (vm::find-code-object function))             (vm::find-code-object function))
580         (not (eq closure function))))         (not (eq closure function))))
581    
582    (defun genericp (fn)
583      (typep fn 'generic-function))
584    
585  (defun struct-closure-p (function)  (defun struct-closure-p (function)
586    (or (function-code-object= function #'kernel::structure-slot-accessor)    (or (function-code-object= function #'kernel::structure-slot-accessor)
587        (function-code-object= function #'kernel::structure-slot-setter)        (function-code-object= function #'kernel::structure-slot-setter)
# Line 609  The second return value is the condition Line 611  The second return value is the condition
611       (coerce (if (consp constructor) (car constructor) constructor)       (coerce (if (consp constructor) (car constructor) constructor)
612               'function))))               'function))))
613    
614  (defun genericp (fn)  (defun function-location (function)
615    (typep fn 'generic-function))    "Return the source location for FUNCTION."
   
 (defun gf-definition-location (gf)  
   (flet ((guess-source-file (faslfile)  
            (unix-truename  
             (merge-pathnames (make-pathname :type "lisp")  
                              faslfile))))  
     (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)))  
         (cons  
          (destructuring-bind ((dg name) pathname) def-source  
            (declare (ignore dg))  
            (etypecase pathname  
              (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."  
616    ;; First test if FUNCTION is a closure created by defstruct; if so    ;; First test if FUNCTION is a closure created by defstruct; if so
617    ;; extract the defstruct-description (dd) from the closure and find    ;; extract the defstruct-description (dd) from the closure and find
618    ;; 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 622  The second return value is the condition
622    ;; For an ordinary function we return the source location of the    ;; For an ordinary function we return the source location of the
623    ;; first code-location we find.    ;; first code-location we find.
624    (cond ((struct-closure-p function)    (cond ((struct-closure-p function)
625           (list           (safe-definition-finding
626            (safe-definition-finding            (dd-source-location (struct-closure-dd function))))
            (dd-source-location (struct-closure-dd function)))))  
627          ((genericp function)          ((genericp function)
628           (gf-source-locations function))           (gf-location function))
629          (t          (t
630           (list           (multiple-value-bind (code-location error)
631            (multiple-value-bind (code-location error)               (safe-definition-finding (function-first-code-location function))
632                (safe-definition-finding (function-first-code-location function))             (cond (error (list :error (princ-to-string error)))
633              (cond (error (list :error (princ-to-string error)))                   (t (code-location-source-location code-location)))))))
634                    (t (code-location-source-location code-location))))))))  
635    (defun method-location (method)
636  (defun function-source-location (function)    (function-location (or (pcl::method-fast-function method)
637    (destructuring-bind (first) (function-source-locations function)                           (pcl:method-function method))))
638      first))  
639    (defun method-dspec (method)
640  (defslimefun find-function-locations (symbol-name)    (let* ((gf (pcl:method-generic-function method))
641    "Return a list of source-locations for SYMBOL-NAME's functions."           (name (pcl:generic-function-name gf))
642    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)           (specializers (pcl:method-specializers method)))
643      (cond ((not foundp)      `(method ,name ,(pcl::unparse-specializers specializers))))
644             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))  
645            ((macro-function symbol)  (defun method-definition (method)
646             (function-source-locations (macro-function symbol)))    (list (method-dspec method)
647            ((special-operator-p symbol)          (method-location method)))
648             (list (list :error (format nil "~A is a special-operator" symbol))))  
649            ((fboundp symbol)  (defun make-name-in-file-location (file string)
650             (function-source-locations (coerce symbol 'function)))    (multiple-value-bind (filename c)
651            (t (list (list :error        (ignore-errors (unix-truename
652                           (format nil "Symbol not fbound: ~A" symbol-name))))                        (merge-pathnames (make-pathname :type "lisp")
653            )))                                         file)))
654        (cond (filename (make-location `(:file ,filename)
655                                       `(:function-name ,string)))
656              (t (list :error (princ-to-string c))))))
657    
658    (defun gf-location (gf)
659      (let ((def-source (pcl::definition-source gf))
660            (name (string (pcl:generic-function-name gf))))
661        (etypecase def-source
662          (pathname (make-name-in-file-location def-source name))
663          (cons
664           (destructuring-bind ((dg name) pathname) def-source
665             (declare (ignore dg))
666             (etypecase pathname
667               (pathname (make-name-in-file-location pathname (string name)))
668               (null `(:error ,(format nil "Cannot resolve: ~S" def-source)))))))))
669    
670    (defun gf-method-definitions (gf)
671      (mapcar #'method-definition (pcl::generic-function-methods gf)))
672    
673    (defun function-definitions (symbol)
674      "Return definitions in the \"function namespace\", i.e.,
675    regular functions, generic functions, methods and macros."
676      (cond ((macro-function symbol)
677             (list `((defmacro ,symbol)
678                     ,(function-location (macro-function symbol)))))
679            ((special-operator-p symbol)
680             (list `((:special-operator ,symbol)
681                     (:error ,(format nil "Don't know where `~A' is defined"
682                                      symbol)))))
683            ((fboundp symbol)
684             (let ((function (coerce symbol 'function)))
685               (cond ((genericp function)
686                      (cons (list `(defgeneric ,symbol)
687                                  (function-location function))
688                            (gf-method-definitions function)))
689                     (t (list (list `(function ,symbol)
690                                    (function-location function)))))))))
691    
692    (defimplementation find-definitions (symbol)
693      (function-definitions symbol))
694    
695    
696  ;;;; Documentation.  ;;;; Documentation.
697    
698  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
699    (let ((result '()))    (let ((result '()))
700      (flet ((doc (kind)      (flet ((doc (kind)
701               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 734  The second return value is the condition Line 741  The second return value is the condition
741                         (doc nil)))                         (doc nil)))
742        result)))        result)))
743    
744  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
745    (print-description-to-string    (ecase namespace
746     (or (ext:info setf inverse (from-string symbol-name))      (:variable
747         (ext:info setf expander (from-string symbol-name)))))       (describe symbol))
748        ((:function :generic-function)
749  (defslimefun describe-type (symbol-name)       (describe (symbol-function symbol)))
750    (print-description-to-string      (:setf
751     (kernel:values-specifier-type (from-string symbol-name))))       (describe (or (ext:info setf inverse symbol))
752                   (ext:info setf expander symbol)))
753  (defslimefun describe-class (symbol-name)      (:type
754    (print-description-to-string (find-class (from-string symbol-name) nil)))       (describe (kernel:values-specifier-type symbol)))
755        (:class
756  (defslimefun describe-alien-type (symbol-name)       (describe (find-class symbol)))
757    (let ((name (from-string symbol-name)))      (:alien-type
758      (ecase (ext:info :alien-type :kind name)       (ecase (ext:info :alien-type :kind symbol)
759        (:primitive         (:primitive
760         (print-description-to-string          (describe (let ((alien::*values-type-okay* t))
761          (let ((alien::*values-type-okay* t))                      (funcall (ext:info :alien-type :translator symbol)
762            (funcall (ext:info :alien-type :translator name) (list name)))))                               (list symbol)))))
763        ((:defined)         ((:defined)
764         (print-description-to-string (ext:info :alien-type :definition name)))          (describe (ext:info :alien-type :definition symbol)))
765        (:unknown         (:unknown
766         (format nil "Unkown alien type: ~A" symbol-name)))))          (format nil "Unkown alien type: ~S" symbol))))
767        (:alien-struct
768  (defmacro %describe-alien (symbol-name namespace)       (describe (ext:info :alien-type :struct symbol)))
769    `(print-description-to-string      (:alien-union
770      (ext:info :alien-type ,namespace (from-string ,symbol-name))))       (describe (ext:info :alien-type :union symbol)))
771        (:alien-enum
772  (defslimefun describe-alien-struct (symbol-name)       (describe (ext:info :alien-type :enum symbol)))))
773    (%describe-alien symbol-name :struct))  
774    (defimplementation arglist (symbol)
775  (defslimefun describe-alien-union (symbol-name)    (let* ((fun (or (macro-function symbol)
776    (%describe-alien symbol-name :union))                    (symbol-function symbol)))
777             (arglist
778  (defslimefun describe-alien-enum (symbol-name)            (cond ((eval:interpreted-function-p fun)
779    (%describe-alien symbol-name :enum))                   (eval:interpreted-function-arglist fun))
780                    ((pcl::generic-function-p fun)
781  (defmethod arglist-string (fname)                   (pcl:generic-function-lambda-list fun))
782    "Return a string describing the argument list for FNAME.                  ((kernel:%function-arglist (kernel:%function-self fun)))
783  The result has the format \"(...)\"."                  ;; this should work both for
784    (declare (type string fname))                  ;; compiled-debug-function and for
785    (multiple-value-bind (function condition)                  ;; interpreted-debug-function
786        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))                  (t (let ((df (di::function-debug-function fun)))
787      (when condition                       (if df
788        (return-from arglist-string (format nil "(-- ~A)" condition)))                           (di::debug-function-lambda-list df)
789      (let ((arglist                           "(<arglist-unavailable>)"))))))
790             (if (not (or (fboundp function)      (check-type arglist (or list string))
791                          (functionp function)))      arglist))
                "(-- <Unknown-Function>)"  
                (let* ((fun (or (macro-function function)  
                                (symbol-function function)))  
                       (df (di::function-debug-function fun))  
                       (arglist (kernel:%function-arglist fun)))  
                  (cond ((eval:interpreted-function-p fun)  
                         (eval:interpreted-function-arglist fun))  
                        ((pcl::generic-function-p fun)  
                         (pcl::gf-pretty-arglist fun))  
                        (arglist arglist)  
                        ;; this should work both for  
                        ;; compiled-debug-function and for  
                        ;; interpreted-debug-function  
                        (df (di::debug-function-lambda-list df))  
                        (t "(<arglist-unavailable>)"))))))  
       (if (stringp arglist)  
           arglist  
           (to-string arglist)))))  
792    
793    
794  ;;;; Miscellaneous.  ;;;; Miscellaneous.
795    
796  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
797    (walker:macroexpand-all form))    (walker:macroexpand-all form))
798    
799  (defun tracedp (fname)  ;; (in-package :c)
800    (gethash (debug::trace-fdefinition fname)  ;;
801             debug::*traced-functions*))  ;; (defun swank-backend::expand-ir1-top-level (form)
802    ;;   "A scaled down version of the first pass of the compiler."
803  (defslimefun toggle-trace-fdefinition (fname-string)  ;;   (with-compilation-unit ()
804    (let ((fname (from-string fname-string)))  ;;     (let* ((*lexical-environment*
805      (cond ((tracedp fname)  ;;             (make-lexenv :default (make-null-environment)
806             (debug::untrace-1 fname)  ;;                          :cookie *default-cookie*
807             (format nil "~S is now untraced." fname))  ;;                          :interface-cookie *default-interface-cookie*))
808            (t  ;;            (*source-info* (make-lisp-source-info form))
809             (debug::trace-1 fname (debug::make-trace-info))  ;;            (*block-compile* nil)
810             (format nil "~S is now traced." fname)))))  ;;            (*block-compile-default* nil))
811    ;;       (with-ir1-namespace
812    ;;           (clear-stuff)
813    ;;         (find-source-paths form 0)
814    ;;         (ir1-top-level form '(0) t)))))
815    ;;
816    ;; (in-package :swank-backend)
817    ;;
818    ;; (defun print-ir1-converted-blocks (form)
819    ;;   (with-output-to-string (*standard-output*)
820    ;;     (c::print-all-blocks (expand-ir1-top-level (from-string form)))))
821    ;;
822    ;; (defun print-compilation-trace (form)
823    ;;   (with-output-to-string (*standard-output*)
824    ;;     (with-input-from-string (s form)
825    ;;       (ext:compile-from-stream s
826    ;;                                :verbose t
827    ;;                                :progress t
828    ;;                                :trace-stream *standard-output*))))
829    
830  (defslimefun set-default-directory (directory)  (defun set-default-directory (directory)
831    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
832    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
833    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
834    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
835    (namestring (ext:default-directory)))    (namestring (ext:default-directory)))
836    
837    ;;; source-path-{stream,file,string,etc}-position moved into
838  ;;;; 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))))))  
839    
840  (defun code-location-stream-position (code-location stream)  (defun code-location-stream-position (code-location stream)
841    "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 902  to find the position of the correspondin
902    (safe-definition-finding    (safe-definition-finding
903     (source-location-from-code-location code-location)))     (source-location-from-code-location code-location)))
904    
 (defslimefun getpid ()  
   (unix:unix-getpid))  
   
905    
906  ;;;; Debugging  ;;;; Debugging
907    
908  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
909    
910  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
911    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
912    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
913           (*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))  
914      (handler-bind ((di:debug-condition      (handler-bind ((di:debug-condition
915                      (lambda (condition)                      (lambda (condition)
916                        (signal (make-condition                        (signal (make-condition
# Line 1021  to find the position of the correspondin Line 918  to find the position of the correspondin
918                                 :original-condition condition)))))                                 :original-condition condition)))))
919        (funcall debugger-loop-fn))))        (funcall debugger-loop-fn))))
920    
 (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*)))  
   
921  (defun nth-frame (index)  (defun nth-frame (index)
922    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (di:frame-down frame))
923         (i index (1- i)))         (i index (1- i)))
924        ((zerop i) frame)))        ((zerop i) frame)))
925    
926  (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  
 stack."  
927    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
928      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (di:frame-down f)
929            for i from start below end            for i from start below end
930            while f            while f
931            collect f)))            collect f)))
932    
933  (defmethod backtrace (start end)  (defimplementation print-frame (frame stream)
934    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (let ((*standard-output* stream))
935        (debug::print-frame-call frame :verbosity 1 :number nil)))
936    
937  (defmethod debugger-info-for-emacs (start end)  (defimplementation frame-source-location-for-emacs (index)
   (list (format-condition-for-emacs)  
         (format-restarts-for-emacs)  
         (backtrace start end)))  
   
 (defmethod frame-source-location-for-emacs (index)  
938    (code-location-source-location (di:frame-code-location (nth-frame index))))    (code-location-source-location (di:frame-code-location (nth-frame index))))
939    
940  (defmethod eval-in-frame (form index)  (defimplementation eval-in-frame (form index)
941    (di:eval-in-frame (nth-frame index) form))    (di:eval-in-frame (nth-frame index) form))
942    
943  (defslimefun pprint-eval-string-in-frame (string index)  (defimplementation frame-locals (index)
   (swank-pprint  
    (multiple-value-list  
     (di:eval-in-frame (nth-frame index) (from-string string)))))  
   
 (defslimefun inspect-in-frame (string index)  
   (reset-inspector)  
   (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))  
   
 (defmethod frame-locals (index)  
944    (let* ((frame (nth-frame index))    (let* ((frame (nth-frame index))
945           (location (di:frame-code-location frame))           (location (di:frame-code-location frame))
946           (debug-function (di:frame-debug-function frame))           (debug-function (di:frame-debug-function frame))
947           (debug-variables (di::debug-function-debug-variables debug-function)))           (debug-variables (di::debug-function-debug-variables debug-function)))
948      (loop for v across debug-variables      (loop for v across debug-variables collect
949            collect (list            (list :name (di:debug-variable-symbol v)
950                     :symbol (di:debug-variable-symbol v)                  :id (di:debug-variable-id v)
951                     :id (di:debug-variable-id v)                  :value (ecase (di:debug-variable-validity v location)
952                     :value-string                           (:valid
953                     (if (eq (di:debug-variable-validity v location)                            (di:debug-variable-value v frame))
954                             :valid)                           ((:invalid :unknown)
955                         (to-string (di:debug-variable-value v frame))                            ':not-available))))))
956                         "<not-available>")))))  
957    (defimplementation frame-catch-tags (index)
958  (defmethod frame-catch-tags (index)    (mapcar #'car (di:frame-catches (nth-frame index))))
959    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  
960          collect `(,tag . ,(code-location-source-location code-location))))  (defun set-step-breakpoints (frame)
961      (when (di:debug-block-elsewhere-p (di:code-location-debug-block
962                                         (di:frame-code-location frame)))
963        (error "Cannot step, in elsewhere code~%"))
964      (let* ((code-location (di:frame-code-location frame))
965             (debug::*bad-code-location-types*
966              (remove :call-site debug::*bad-code-location-types*))
967             (next (debug::next-code-locations code-location)))
968        (cond (next
969               (let ((steppoints '()))
970                 (flet ((hook (frame breakpoint)
971                          (let ((debug:*stack-top-hint* frame))
972                            (mapc #'di:delete-breakpoint steppoints)
973                            (let ((cl (di::breakpoint-what breakpoint)))
974                              (break "Breakpoint: ~S ~S"
975                                     (di:code-location-kind cl)
976                                     (di::compiled-code-location-pc cl))))))
977                   (dolist (code-location next)
978                     (let ((bp (di:make-breakpoint #'hook code-location
979                                                   :kind :code-location)))
980                       (di:activate-breakpoint bp)
981                       (push bp steppoints))))))
982             (t
983              (flet ((hook (frame breakpoint values cookie)
984                       (declare (ignore cookie))
985                       (di:delete-breakpoint breakpoint)
986                       (let ((debug:*stack-top-hint* frame))
987                         (break "Function-end: ~A ~A" breakpoint values))))
988                (let* ((debug-function (di:frame-debug-function frame))
989                       (bp (di:make-breakpoint #'hook debug-function
990                                               :kind :function-end)))
991                  (di:activate-breakpoint bp)))))))
992    
993    ;; (defslimefun sldb-step (frame)
994    ;;   (cond ((find-restart 'continue *swank-debugger-condition*)
995    ;;          (set-step-breakpoints (nth-frame frame))
996    ;;          (continue *swank-debugger-condition*))
997    ;;         (t
998    ;;          (error "Cannot continue in from condition: ~A"
999    ;;                 *swank-debugger-condition*))))
1000    
1001    (defun frame-cfp (frame)
1002      "Return the Control-Stack-Frame-Pointer for FRAME."
1003      (etypecase frame
1004        (di::compiled-frame (di::frame-pointer frame))
1005        ((or di::interpreted-frame null) -1)))
1006    
1007    (defun frame-ip (frame)
1008      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1009      (if (not frame)
1010          -1
1011          (let ((debug-fun (di::frame-debug-function frame)))
1012            (etypecase debug-fun
1013              (di::compiled-debug-function
1014               (let* ((code-loc (di:frame-code-location frame))
1015                      (component (di::compiled-debug-function-component debug-fun))
1016                      (pc (di::compiled-code-location-pc code-loc))
1017                      (ip (sys:without-gcing
1018                           (sys:sap-int
1019                            (sys:sap+ (kernel:code-instructions component) pc)))))
1020                 (values ip pc)))
1021              ((or di::bogus-debug-function di::interpreted-debug-function)
1022               -1)))))
1023    
1024    (defun frame-registers (frame)
1025      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1026      (let* ((cfp (frame-cfp frame))
1027             (csp (frame-cfp (di::frame-up frame)))
1028             (ip (frame-ip frame))
1029             (ocfp (frame-cfp (di::frame-down frame)))
1030             (lra (frame-ip (di::frame-down frame))))
1031        (values csp cfp ip ocfp lra)))
1032    
1033    (defun print-frame-registers (frame-number)
1034      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1035        (flet ((fixnum (p) (etypecase p
1036                             (integer p)
1037                             (sys:system-area-pointer (sys:sap-int p)))))
1038          (apply #'format t "~
1039    CSP  =  ~X
1040    CFP  =  ~X
1041    IP   =  ~X
1042    OCFP =  ~X
1043    LRA  =  ~X~%" (mapcar #'fixnum
1044                          (multiple-value-list (frame-registers frame)))))))
1045    
1046    
1047    (defimplementation disassemble-frame (frame-number)
1048      "Return a string with the disassembly of frames code."
1049      (print-frame-registers frame-number)
1050      (terpri)
1051      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1052             (debug-fun (di::frame-debug-function frame)))
1053        (etypecase debug-fun
1054          (di::compiled-debug-function
1055           (let* ((component (di::compiled-debug-function-component debug-fun))
1056                  (fun (di:debug-function-function debug-fun)))
1057             (if fun
1058                 (disassemble fun)
1059                 (disassem:disassemble-code-component component))))
1060          (di::bogus-debug-function
1061           (format t "~%[Disassembling bogus frames not implemented]")))))
1062    
1063    #+(or)
1064    (defun print-binding-stack ()
1065      (flet ((bsp- (p) (sys:sap+ p (- (* vm:binding-size vm:word-bytes))))
1066             (frob (p offset) (kernel:make-lisp-obj (sys:sap-ref-32 p offset))))
1067        (do ((bsp (bsp- (kernel:binding-stack-pointer-sap)) (bsp- bsp))
1068             (start (sys:int-sap (lisp::binding-stack-start))))
1069            ((sys:sap= bsp start))
1070          (format t "~X:  ~S = ~S~%"
1071                  (sys:sap-int bsp)
1072                  (frob bsp (* vm:binding-symbol-slot vm:word-bytes))
1073                  (frob bsp (* vm:binding-value-slot vm:word-bytes))))))
1074    
1075    ;; (print-binding-stack)
1076    
1077    #+(or)
1078    (defun print-catch-blocks ()
1079      (do ((b (di::descriptor-sap lisp::*current-catch-block*)
1080              (sys:sap-ref-sap b (* vm:catch-block-previous-catch-slot
1081                                    vm:word-bytes))))
1082          (nil)
1083        (let ((int (sys:sap-int b)))
1084          (when (zerop int) (return))
1085          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1086            (let ((uwp (ref vm:catch-block-current-uwp-slot))
1087                  (cfp (ref vm:catch-block-current-cont-slot))
1088                  (tag (ref vm:catch-block-tag-slot))
1089                  )
1090          (format t "~X:  uwp = ~8X  cfp = ~8X  tag = ~X~%"
1091                  int uwp cfp (kernel:make-lisp-obj tag)))))))
1092    
1093    ;; (print-catch-blocks)
1094    
1095    #+(or)
1096    (defun print-unwind-blocks ()
1097      (do ((b (di::descriptor-sap lisp::*current-unwind-protect-block*)
1098              (sys:sap-ref-sap b (* vm:unwind-block-current-uwp-slot
1099                                    vm:word-bytes))))
1100          (nil)
1101        (let ((int (sys:sap-int b)))
1102          (when (zerop int) (return))
1103          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1104            (let ((cfp (ref vm:unwind-block-current-cont-slot)))
1105              (format t "~X:  cfp = ~X~%" int cfp))))))
1106    
1107  (defslimefun invoke-nth-restart (index)  ;; (print-unwind-blocks)
   (invoke-restart-interactively (nth-restart index)))  
   
 (defslimefun sldb-abort ()  
   (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))  
1108    
1109    
1110  ;;;; Inspecting  ;;;; Inspecting
1111    
 (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)  
   (reset-inspector)  
   (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)  
           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))))))  
1112  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1113    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1114      vm:function-pointer-type      vm:function-pointer-type
# Line 1168  stack." Line 1133  stack."
1133       (append (apropos-list "-TYPE" "VM" t)       (append (apropos-list "-TYPE" "VM" t)
1134               (apropos-list "-TYPE" "BIGNUM" t)))))               (apropos-list "-TYPE" "BIGNUM" t)))))
1135    
1136  (defun describe-primitive-type (object)  
1137    (defimplementation describe-primitive-type (object)
1138    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1139      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1140             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1141        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1142        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1143                                    vm:function-pointer-type                                   vm:function-pointer-type
1144                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
1145                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
1146                                    ))                                   ))
1147               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
1148                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
1149                                         :key #'symbol-value)))                                    :key #'symbol-value)))
1150                 (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*))  
            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."))  
1151    
1152  (defmethod inspected-parts (o)  (defimplementation inspected-parts (o)
1153    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
1154           (inspected-parts-of-value-cell o))           (inspected-parts-of-value-cell o))
1155          (t          (t
# Line 1235  nil if there's no second element." Line 1167  nil if there's no second element."
1167    (values (format nil "~A~% is a value cell." o)    (values (format nil "~A~% is a value cell." o)
1168            (list (cons "Value" (c:value-cell-ref o)))))            (list (cons "Value" (c:value-cell-ref o)))))
1169    
 ;; 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.~%")))))))  
   
1170  (defmethod inspected-parts ((o function))  (defmethod inspected-parts ((o function))
1171    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
1172      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
# Line 1304  nil if there's no second element." Line 1203  nil if there's no second element."
1203            `(("Name" . ,(kernel:fdefn-name o))            `(("Name" . ,(kernel:fdefn-name o))
1204              ("Function" . ,(kernel:fdefn-function o)))))              ("Function" . ,(kernel:fdefn-function o)))))
1205    
1206  ;;; Local Variables:  
1207  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))  ;;;; Profiling
1208  ;;; End:  (defimplementation profile (fname)
1209      (eval `(profile:profile ,fname)))
1210    
1211    (defimplementation unprofile (fname)
1212      (eval `(profile:unprofile ,fname)))
1213    
1214    (defimplementation unprofile-all ()
1215      (profile:unprofile)
1216      "All functions unprofiled.")
1217    
1218    (defimplementation profile-report ()
1219      (profile:report-time))
1220    
1221    (defimplementation profile-reset ()
1222      (profile:reset-time)
1223      "Reset profiling counters.")
1224    
1225    (defimplementation profiled-functions ()
1226      profile:*timed-functions*)
1227    
1228    (defimplementation profile-package (package callers methods)
1229      (profile:profile-all :package package
1230                           :callers-p callers
1231                           :methods methods))
1232    
1233    
1234    ;;;; Multiprocessing
1235    
1236    #+MP
1237    (progn
1238      (defimplementation startup-multiprocessing ()
1239        ;; Threads magic: this never returns! But top-level becomes
1240        ;; available again.
1241        (mp::startup-idle-and-top-level-loops))
1242    
1243      (defimplementation spawn (fn &key (name "Anonymous"))
1244        (mp:make-process fn :name name))
1245    
1246      (defimplementation thread-name (thread)
1247        (mp:process-name thread))
1248    
1249      (defimplementation thread-status (thread)
1250        (mp:process-whostate thread))
1251    
1252      (defimplementation current-thread ()
1253        mp:*current-process*)
1254    
1255      (defimplementation all-threads ()
1256        (copy-list mp:*all-processes*))
1257    
1258      (defimplementation interrupt-thread (thread fn)
1259        (mp:process-interrupt thread fn))
1260    
1261      (defimplementation kill-thread (thread)
1262        (mp:destroy-process thread))
1263    
1264      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
1265    
1266      (defstruct (mailbox (:conc-name mailbox.))
1267        (mutex (mp:make-lock "process mailbox"))
1268        (queue '() :type list))
1269    
1270      (defun mailbox (thread)
1271        "Return THREAD's mailbox."
1272        (mp:with-lock-held (*mailbox-lock*)
1273          (or (getf (mp:process-property-list thread) 'mailbox)
1274              (setf (getf (mp:process-property-list thread) 'mailbox)
1275                    (make-mailbox)))))
1276    
1277      (defimplementation send (thread message)
1278        (let* ((mbox (mailbox thread))
1279               (mutex (mailbox.mutex mbox)))
1280          (mp:with-lock-held (mutex)
1281            (setf (mailbox.queue mbox)
1282                  (nconc (mailbox.queue mbox) (list message))))))
1283    
1284      (defimplementation receive ()
1285        (let* ((mbox (mailbox mp:*current-process*))
1286               (mutex (mailbox.mutex mbox)))
1287          (mp:process-wait "receive" #'mailbox.queue mbox)
1288          (mp:with-lock-held (mutex)
1289            (pop (mailbox.queue mbox)))))
1290    
1291      )

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

  ViewVC Help
Powered by ViewVC 1.1.5