/[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.216 by heller, Tue Dec 22 09:31:15 2009 UTC
# Line 1  Line 1 
1  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-  ;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
2    ;;;
3    ;;; License: Public Domain
4    ;;;
5    ;;;; Introduction
6    ;;;
7    ;;; This is the CMUCL implementation of the `swank-backend' package.
8    
9    (in-package :swank-backend)
10    
11  (declaim (optimize debug))  (import-swank-mop-symbols :pcl '(:slot-definition-documentation))
12    
13  (in-package :swank)  (defun swank-mop:slot-definition-documentation (slot)
14      (documentation slot t))
15    
16  ;; Turn on xref. [should we?]  ;;;; "Hot fixes"
17  (setf c:*record-xref-info* t)  ;;;
18    ;;; Here are necessary bugfixes to the oldest supported version of
19    ;;; CMUCL (currently 18e). Any fixes placed here should also be
20    ;;; submitted to the `cmucl-imp' mailing list and confirmed as
21    ;;; good. When a new release is made that includes the fixes we should
22    ;;; promptly delete them from here. It is enough to be compatible with
23    ;;; the latest release.
24    
25  (defun without-interrupts* (body)  (in-package :lisp)
   (sys:without-interrupts (funcall body)))  
26    
27  (defun set-fd-non-blocking (fd)  ;;; `READ-SEQUENCE' with large sequences has problems in 18e. This new
28    (flet ((fcntl (fd cmd arg)  ;;; definition works better.
            (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)  
              (or flags  
                  (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))  
     (let ((flags (fcntl fd unix:F-GETFL 0)))  
       (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))  
29    
30    #-cmu19
31  ;;;; TCP server.  (progn
32      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
33        (when s
34          (setf (symbol-value s) nil)))
35    
36      (defun read-into-simple-string (s stream start end)
37        (declare (type simple-string s))
38        (declare (type stream stream))
39        (declare (type index start end))
40        (unless (subtypep (stream-element-type stream) 'character)
41          (error 'type-error
42                 :datum (read-char stream nil #\Null)
43                 :expected-type (stream-element-type stream)
44                 :format-control "Trying to read characters from a binary stream."))
45        ;; Let's go as low level as it seems reasonable.
46        (let* ((numbytes (- end start))
47               (total-bytes 0))
48          ;; read-n-bytes may return fewer bytes than requested, so we need
49          ;; to keep trying.
50          (loop while (plusp numbytes) do
51                (let ((bytes-read (system:read-n-bytes stream s start numbytes nil)))
52                  (when (zerop bytes-read)
53                    (return-from read-into-simple-string total-bytes))
54                  (incf total-bytes bytes-read)
55                  (incf start bytes-read)
56                  (decf numbytes bytes-read)))
57          total-bytes))
58    
59      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
60        (when s
61          (setf (symbol-value s) t)))
62    
63  (defun resolve-hostname (name)    )
64    (let* ((hostent (ext:lookup-host-entry name))  
65           (address (car (ext:host-entry-addr-list hostent))))  (in-package :swank-backend)
66      (ext:htonl address)))  
67    
68  (defun create-swank-server (port &key (reuse-address t)  ;;;; TCP server
69                              (address "localhost"))  ;;;
70    "Create a SWANK TCP server."  ;;; In CMUCL we support all communication styles. By default we use
71    (let* ((ip (resolve-hostname address))  ;;; `:SIGIO' because it is the most responsive, but it's somewhat
72           (fd (ext:create-inet-listener port :stream  ;;; dangerous: CMUCL is not in general "signal safe", and you don't
73                                         :reuse-address reuse-address  ;;; know for sure what you'll be interrupting. Both `:FD-HANDLER' and
74                                         :host ip)))  ;;; `:SPAWN' are reasonable alternatives.
75      (system:add-fd-handler fd :input #'accept-connection)  
76      (nth-value 1 (ext::get-socket-host-and-port fd))))  (defimplementation preferred-communication-style ()
77      :sigio)
78  (defun accept-connection (socket)  
79    "Accept one Swank TCP connection on SOCKET and then close it."  #-(or darwin mips)
80    (setup-request-handler (ext:accept-tcp-connection socket))  (defimplementation create-socket (host port)
81    (sys:invalidate-descriptor socket)    (let* ((addr (resolve-hostname host))
82    (unix:unix-close socket))           (addr (if (not (find-symbol "SOCKET-ERROR" :ext))
83                       (ext:htonl addr)
84  (defun open-stream-to-emacs ()                     addr)))
85    "Return an output-stream to Emacs' output buffer."      (ext:create-inet-listener port :stream :reuse-address t :host addr)))
86    (let* ((ip (resolve-hostname "localhost"))  
87           (listener (ext:create-inet-listener 0 :stream :host ip))  ;; There seems to be a bug in create-inet-listener on Mac/OSX and Irix.
88           (port (nth-value 1 (ext::get-socket-host-and-port listener))))  #+(or darwin mips)
89      (unwind-protect  (defimplementation create-socket (host port)
90           (progn    (declare (ignore host))
91             (eval-in-emacs `(slime-open-stream-to-lisp ,port))    (ext:create-inet-listener port :stream :reuse-address t))
92             (let ((fd (ext:accept-tcp-connection listener)))  
93               (sys:make-fd-stream fd :output t)))  (defimplementation local-port (socket)
94        (ext:close-socket listener))))    (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
95    
96  (defvar *use-dedicated-output-stream* t)  (defimplementation close-socket (socket)
97      (let ((fd (socket-fd socket)))
98  (defun setup-request-handler (socket)      (sys:invalidate-descriptor fd)
99    "Setup request handling for SOCKET."      (ext:close-socket fd)))
100    (let* ((stream (sys:make-fd-stream socket  
101                                       :input t :output t  (defimplementation accept-connection (socket &key
102                                       :element-type 'base-char))                                        external-format buffering timeout)
103           (input (make-slime-input-stream))    (declare (ignore timeout))
104           (output (if *use-dedicated-output-stream*    (make-socket-io-stream (ext:accept-tcp-connection socket)
105                       (let ((*emacs-io* stream)) (open-stream-to-emacs))                           (or buffering :full)
106                       (make-slime-output-stream)))                           (or external-format :iso-8859-1)))
107           (io (make-two-way-stream input output)))  
108      (system:add-fd-handler socket  ;;;;; Sockets
109                             :input (lambda (fd)  
110                                      (declare (ignore fd))  (defimplementation socket-fd (socket)
111                                      (serve-request stream output input io)))))    "Return the filedescriptor for the socket represented by SOCKET."
112      (etypecase socket
113  (defun serve-request (*emacs-io* *slime-output* *slime-input* *slime-io*)      (fixnum socket)
114    "Read and process a request from a SWANK client.      (sys:fd-stream (sys:fd-stream-fd socket))))
115  The request is read from the socket as a sexp and then evaluated."  
116    (catch 'slime-toplevel  (defun resolve-hostname (hostname)
117      (with-simple-restart (abort "Return to Slime toplevel.")    "Return the IP address of HOSTNAME as an integer (in host byte-order)."
118        (handler-case (read-from-emacs)    (let ((hostent (ext:lookup-host-entry hostname)))
119          (slime-read-error (e)      (car (ext:host-entry-addr-list hostent))))
120            (when *swank-debug-p*  
121              (format *debug-io* "~&;; Connection to Emacs lost.~%;; [~A]~%" e))  (defvar *external-format-to-coding-system*
122            (sys:invalidate-descriptor (sys:fd-stream-fd *emacs-io*))    '((:iso-8859-1
123            (close *emacs-io*)))))       "latin-1" "latin-1-unix" "iso-latin-1-unix"
124    (sys:scrub-control-stack))       "iso-8859-1" "iso-8859-1-unix")
125        #+unicode
126        (:utf-8 "utf-8" "utf-8-unix")))
127    
128    (defimplementation find-external-format (coding-system)
129      (car (rassoc-if (lambda (x) (member coding-system x :test #'equal))
130                      *external-format-to-coding-system*)))
131    
132    (defun make-socket-io-stream (fd buffering external-format)
133      "Create a new input/output fd-stream for FD."
134      #-unicode(declare (ignore external-format))
135      (sys:make-fd-stream fd :input t :output t :element-type 'base-char
136                          :buffering buffering
137                          #+unicode :external-format
138                          #+unicode external-format))
139    
140    (defimplementation make-fd-stream (fd external-format)
141      (make-socket-io-stream fd :full external-format))
142    
143    (defimplementation dup (fd)
144      (multiple-value-bind (clone error) (unix:unix-dup fd)
145        (unless clone (error "dup failed: ~a" (unix:get-unix-error-msg error)))
146        clone))
147    
148    (defimplementation command-line-args ()
149      ext:*command-line-strings*)
150    
151    (defimplementation exec-image (image-file args)
152      (multiple-value-bind (ok error)
153          (unix:unix-execve (car (command-line-args))
154                            (list* (car (command-line-args))
155                                   "-core" image-file
156                                   "-noinit"
157                                   args))
158        (error "~a" (unix:get-unix-error-msg error))
159        ok))
160    
161    ;;;;; Signal-driven I/O
162    
163    (defimplementation install-sigint-handler (function)
164      (sys:enable-interrupt :sigint (lambda (signal code scp)
165                                      (declare (ignore signal code scp))
166                                      (funcall function))))
167    
168    (defvar *sigio-handlers* '()
169      "List of (key . function) pairs.
170    All functions are called on SIGIO, and the key is used for removing
171    specific functions.")
172    
173    (defun reset-sigio-handlers () (setq *sigio-handlers* '()))
174    ;; All file handlers are invalid afer reload.
175    (pushnew 'reset-sigio-handlers ext:*after-save-initializations*)
176    
177    (defun set-sigio-handler ()
178      (sys:enable-interrupt :sigio (lambda (signal code scp)
179                                     (sigio-handler signal code scp))))
180    
181    (defun sigio-handler (signal code scp)
182      (declare (ignore signal code scp))
183      (mapc #'funcall (mapcar #'cdr *sigio-handlers*)))
184    
185    (defun fcntl (fd command arg)
186      "fcntl(2) - manipulate a file descriptor."
187      (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
188        (cond (ok)
189              (t (error "fcntl: ~A" (unix:get-unix-error-msg error))))))
190    
191    (defimplementation add-sigio-handler (socket fn)
192      (set-sigio-handler)
193      (let ((fd (socket-fd socket)))
194        (fcntl fd unix:f-setown (unix:unix-getpid))
195        (let ((old-flags (fcntl fd unix:f-getfl 0)))
196          (fcntl fd unix:f-setfl (logior old-flags unix:fasync)))
197        (assert (not (assoc fd *sigio-handlers*)))
198        (push (cons fd fn) *sigio-handlers*)))
199    
200    (defimplementation remove-sigio-handlers (socket)
201      (let ((fd (socket-fd socket)))
202        (when (assoc fd *sigio-handlers*)
203          (setf *sigio-handlers* (remove fd *sigio-handlers* :key #'car))
204          (let ((old-flags (fcntl fd unix:f-getfl 0)))
205            (fcntl fd unix:f-setfl (logandc2 old-flags unix:fasync)))
206          (sys:invalidate-descriptor fd))
207        (assert (not (assoc fd *sigio-handlers*)))
208        (when (null *sigio-handlers*)
209          (sys:default-interrupt :sigio))))
210    
211    ;;;;; SERVE-EVENT
212    
213    (defimplementation add-fd-handler (socket fn)
214      (let ((fd (socket-fd socket)))
215        (sys:add-fd-handler fd :input (lambda (_) _ (funcall fn)))))
216    
217    (defimplementation remove-fd-handlers (socket)
218      (sys:invalidate-descriptor (socket-fd socket)))
219    
220    (defimplementation wait-for-input (streams &optional timeout)
221      (assert (member timeout '(nil t)))
222      (loop
223       (let ((ready (remove-if-not #'listen streams)))
224         (when ready (return ready)))
225       (when timeout (return nil))
226       (multiple-value-bind (in out) (make-pipe)
227         (let* ((f (constantly t))
228                (handlers (loop for s in (cons in (mapcar #'to-fd-stream streams))
229                                collect (add-one-shot-handler s f))))
230           (unwind-protect
231                (let ((*interrupt-queued-handler* (lambda ()
232                                                    (write-char #\! out))))
233                  (when (check-slime-interrupts) (return :interrupt))
234                  (sys:serve-event))
235             (mapc #'sys:remove-fd-handler handlers)
236             (close in)
237             (close out))))))
238    
239    (defun to-fd-stream (stream)
240      (etypecase stream
241        (sys:fd-stream stream)
242        (synonym-stream
243         (to-fd-stream
244          (symbol-value (synonym-stream-symbol stream))))
245        (two-way-stream
246         (to-fd-stream (two-way-stream-input-stream stream)))))
247    
248    (defun add-one-shot-handler (stream function)
249      (let (handler)
250        (setq handler (sys:add-fd-handler (sys:fd-stream-fd stream) :input
251                                          (lambda (fd)
252                                            (declare (ignore fd))
253                                            (sys:remove-fd-handler handler)
254                                            (funcall function stream))))))
255    
256    (defun make-pipe ()
257      (multiple-value-bind (in out) (unix:unix-pipe)
258        (values (sys:make-fd-stream in :input t :buffering :none)
259                (sys:make-fd-stream out :output t :buffering :none))))
260    
261    
262  ;;;; Stream handling  ;;;; Stream handling
263    ;;; XXX: How come we don't use Gray streams in CMUCL too? -luke (15/May/2004)
264    
265    (defimplementation make-output-stream (write-string)
266      (make-slime-output-stream write-string))
267    
268    (defimplementation make-input-stream (read-string)
269      (make-slime-input-stream read-string))
270    
271  (defstruct (slime-output-stream  (defstruct (slime-output-stream
272               (:include lisp::lisp-stream               (:include lisp::lisp-stream
273                         (lisp::misc #'sos/misc)                         (lisp::misc #'sos/misc)
274                         (lisp::out #'sos/out)                         (lisp::out #'sos/write-char)
275                         (lisp::sout #'sos/sout))                         (lisp::sout #'sos/write-string))
276               (:conc-name sos.)               (:conc-name sos.)
277               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
278    (buffer (make-string 512) :type string)               (:constructor make-slime-output-stream (output-fn)))
279      (output-fn nil :type function)
280      (buffer (make-string 4000) :type string)
281    (index 0 :type kernel:index)    (index 0 :type kernel:index)
282    (column 0 :type kernel:index))    (column 0 :type kernel:index))
283    
# Line 102  The request is read from the socket as a Line 285  The request is read from the socket as a
285    (declare (ignore d))    (declare (ignore d))
286    (print-unreadable-object (s stream :type t :identity t)))    (print-unreadable-object (s stream :type t :identity t)))
287    
288  (defun sos/out (stream char)  (defun sos/write-char (stream char)
289    (let ((buffer (sos.buffer stream))    (let ((pending-output nil))
290          (index (sos.index stream)))      (system:without-interrupts
291      (setf (schar buffer index) char)        (let ((buffer (sos.buffer stream))
292      (setf (sos.index stream) (1+ index))              (index (sos.index stream)))
293      (incf (sos.column stream))          (setf (schar buffer index) char)
294      (when (char= #\newline char)          (setf (sos.index stream) (1+ index))
295        (setf (sos.column stream) 0))          (incf (sos.column stream))
296      (when (= index (1- (length buffer)))          (when (char= #\newline char)
297        (force-output stream)))            (setf (sos.column stream) 0)
298              #+(or)(setq pending-output (sos/reset-buffer stream))
299              )
300            (when (= index (1- (length buffer)))
301              (setq pending-output (sos/reset-buffer stream)))))
302        (when pending-output
303          (funcall (sos.output-fn stream) pending-output)))
304    char)    char)
305    
306  (defun sos/sout (stream string start end)  (defun sos/write-string (stream string start end)
307    (loop for i from start below end    (loop for i from start below end
308          do (sos/out stream (aref string i))))          do (sos/write-char stream (aref string i))))
309    
310    (defun sos/flush (stream)
311      (let ((string (sos/reset-buffer stream)))
312        (when string
313          (funcall (sos.output-fn stream) string))
314        nil))
315    
316    (defun sos/reset-buffer (stream)
317      (system:without-interrupts
318        (let ((end (sos.index stream)))
319          (unless (zerop end)
320            (prog1 (subseq (sos.buffer stream) 0 end)
321              (setf (sos.index stream) 0))))))
322    
323  (defun sos/misc (stream operation &optional arg1 arg2)  (defun sos/misc (stream operation &optional arg1 arg2)
324    (declare (ignore arg1 arg2))    (declare (ignore arg1 arg2))
325    (case operation    (case operation
326      ((:force-output :finish-output)      ((:force-output :finish-output) (sos/flush stream))
      (let ((end (sos.index stream)))  
        (unless (zerop end)  
          (send-to-emacs `(:read-output ,(subseq (sos.buffer stream) 0 end)))  
          (setf (sos.index stream) 0))))  
327      (:charpos (sos.column stream))      (:charpos (sos.column stream))
328      (:line-length 75)      (:line-length 75)
329      (:file-position nil)      (:file-position nil)
# Line 135  The request is read from the socket as a Line 333  The request is read from the socket as a
333      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
334    
335  (defstruct (slime-input-stream  (defstruct (slime-input-stream
336               (:include string-stream               (:include string-stream
337                         (lisp::in #'sis/in)                         (lisp::in #'sis/in)
338                         (lisp::misc #'sis/misc))                         (lisp::misc #'sis/misc))
339               (:conc-name sis.)               (:conc-name sis.)
340               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
341    (buffer "" :type string)               (:constructor make-slime-input-stream (input-fn)))
342    (index 0 :type kernel:index))    (input-fn nil :type function)
343      (buffer   ""  :type string)
344      (index    0   :type kernel:index))
345    
346  (defun sis/in (stream eof-errorp eof-value)  (defun sis/in (stream eof-errorp eof-value)
   (declare (ignore eof-errorp eof-value))  
347    (let ((index (sis.index stream))    (let ((index (sis.index stream))
348          (buffer (sis.buffer stream)))          (buffer (sis.buffer stream)))
349      (when (= index (length buffer))      (when (= index (length buffer))
350        (setf buffer (slime-read-string))        (let ((string (funcall (sis.input-fn stream))))
351        (setf (sis.buffer stream) buffer)          (cond ((zerop (length string))
352        (setf index 0))                 (return-from sis/in
353                     (if eof-errorp
354                         (error (make-condition 'end-of-file :stream stream))
355                         eof-value)))
356                  (t
357                   (setf buffer string)
358                   (setf (sis.buffer stream) buffer)
359                   (setf index 0)))))
360      (prog1 (aref buffer index)      (prog1 (aref buffer index)
361        (setf (sis.index stream) (1+ index)))))        (setf (sis.index stream) (1+ index)))))
362    
# Line 162  The request is read from the socket as a Line 368  The request is read from the socket as a
368      (:unread (setf (aref (sis.buffer stream)      (:unread (setf (aref (sis.buffer stream)
369                           (decf (sis.index stream)))                           (decf (sis.index stream)))
370                     arg1))                     arg1))
371      (:clear-input (setf (sis.index stream) 0      (:clear-input
372         (setf (sis.index stream) 0
373                          (sis.buffer stream) ""))                          (sis.buffer stream) ""))
374      (:listen (< (sis.index stream) (length (sis.buffer stream))))      (:listen (< (sis.index stream) (length (sis.buffer stream))))
375      (:charpos nil)      (:charpos nil)
376      (:line-length nil)      (:line-length nil)
377      (:get-command nil)      (:get-command nil)
378      (:element-type 'base-char)      (:element-type 'base-char)
379      (:close nil)))      (:close nil)
380        (:interactive-p t)))
381    
382    
383  ;;;; Compilation Commands  ;;;; Compilation Commands
384    
 (defvar *swank-source-info* nil  
   "Bound to a SOURCE-INFO object during compilation.")  
   
385  (defvar *previous-compiler-condition* nil  (defvar *previous-compiler-condition* nil
386    "Used to detect duplicates.")    "Used to detect duplicates.")
387    
388  (defvar *previous-context* nil  (defvar *previous-context* nil
389    "Previous compiler error context.")    "Previous compiler error context.")
390    
391  (defvar *compiler-notes* '()  (defvar *buffer-name* nil
392    "List of compiler notes for the last compilation unit.")    "The name of the Emacs buffer we are compiling from.
393    NIL if we aren't compiling from a buffer.")
394    
 (defvar *buffer-name* nil)  
395  (defvar *buffer-start-position* nil)  (defvar *buffer-start-position* nil)
396  (defvar *buffer-substring* nil)  (defvar *buffer-substring* nil)
 (defvar *compile-filename* nil)  
397    
398    (defimplementation call-with-compilation-hooks (function)
399      (let ((*previous-compiler-condition* nil)
400            (*previous-context* nil)
401            (*print-readably* nil))
402        (handler-bind ((c::compiler-error #'handle-notification-condition)
403                       (c::style-warning  #'handle-notification-condition)
404                       (c::warning        #'handle-notification-condition))
405          (funcall function))))
406    
407    (defimplementation swank-compile-file (input-file output-file
408                                           load-p external-format)
409      (declare (ignore external-format))
410      (clear-xref-info input-file)
411      (with-compilation-hooks ()
412        (let ((*buffer-name* nil)
413              (ext:*ignore-extra-close-parentheses* nil))
414          (multiple-value-bind (output-file warnings-p failure-p)
415              (compile-file input-file :output-file output-file)
416            (values output-file warnings-p
417                    (or failure-p
418                        (when load-p
419                          ;; Cache the latest source file for definition-finding.
420                          (source-cache-get input-file
421                                            (file-write-date input-file))
422                          (not (load output-file)))))))))
423    
424    (defimplementation swank-compile-string (string &key buffer position filename
425                                             policy)
426      (declare (ignore filename policy))
427      (with-compilation-hooks ()
428        (let ((*buffer-name* buffer)
429              (*buffer-start-position* position)
430              (*buffer-substring* string)
431              (source-info (list :emacs-buffer buffer
432                                 :emacs-buffer-offset position
433                                 :emacs-buffer-string string)))
434          (with-input-from-string (stream string)
435            (let ((failurep (ext:compile-from-stream stream :source-info
436                                                    source-info)))
437              (not failurep))))))
438    
439    
440  ;;;;; Trapping notes  ;;;;; Trapping notes
441    ;;;
442    ;;; We intercept conditions from the compiler and resignal them as
443    ;;; `SWANK:COMPILER-CONDITION's.
444    
445  (defun handle-notification-condition (condition)  (defun handle-notification-condition (condition)
446    "Handle a condition caused by a compiler warning.    "Handle a condition caused by a compiler warning."
 This traps all compiler conditions at a lower-level than using  
 C:*COMPILER-NOTIFICATION-FUNCTION*. The advantage is that we get to  
 craft our own error messages, which can omit a lot of redundant  
 information."  
447    (unless (eq condition *previous-compiler-condition*)    (unless (eq condition *previous-compiler-condition*)
448      (let ((context (or (c::find-error-context nil) *previous-context*)))      (let ((context (c::find-error-context nil)))
449        (setq *previous-compiler-condition* condition)        (setq *previous-compiler-condition* condition)
450        (setq *previous-context* context)        (setq *previous-context* context)
451        (signal-compiler-condition condition context))))        (signal-compiler-condition condition context))))
# Line 211  information." Line 455  information."
455             'compiler-condition             'compiler-condition
456             :original-condition condition             :original-condition condition
457             :severity (severity-for-emacs condition)             :severity (severity-for-emacs condition)
458             :message (brief-compiler-message-for-emacs condition context)             :message (compiler-condition-message condition)
459             :location (compiler-note-location context))))             :source-context (compiler-error-context context)
460               :location (if (read-error-p condition)
461                             (read-error-location condition)
462                             (compiler-note-location context)))))
463    
464  (defun severity-for-emacs (condition)  (defun severity-for-emacs (condition)
465    "Return the severity of CONDITION."    "Return the severity of CONDITION."
466    (etypecase condition    (etypecase condition
467        ((satisfies read-error-p) :read-error)
468      (c::compiler-error :error)      (c::compiler-error :error)
469      (c::style-warning :note)      (c::style-warning :note)
470      (c::warning :warning)))      (c::warning :warning)))
471    
472  (defun brief-compiler-message-for-emacs (condition error-context)  (defun read-error-p (condition)
473      (eq (type-of condition) 'c::compiler-read-error))
474    
475    (defun compiler-condition-message (condition)
476    "Briefly describe a compiler error for Emacs.    "Briefly describe a compiler error for Emacs.
477  When Emacs presents the message it already has the source popped up  When Emacs presents the message it already has the source popped up
478  and the source form highlighted. This makes much of the information in  and the source form highlighted. This makes much of the information in
479  the error-context redundant."  the error-context redundant."
480      (princ-to-string condition))
481    
482    (defun compiler-error-context (error-context)
483      "Describe context information for Emacs."
484    (declare (type (or c::compiler-error-context null) error-context))    (declare (type (or c::compiler-error-context null) error-context))
485    (multiple-value-bind (enclosing source)    (multiple-value-bind (enclosing source)
486        (if error-context        (if error-context
487            (values (c::compiler-error-context-enclosing-source error-context)            (values (c::compiler-error-context-enclosing-source error-context)
488                    (c::compiler-error-context-source error-context)))                    (c::compiler-error-context-source error-context)))
489      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"      (if (or enclosing source)
490              enclosing source condition)))          (format nil "~@[--> ~{~<~%--> ~1:;~A ~>~}~%~]~
491                         ~@[==>~{~&~A~}~]"
492                    enclosing source))))
493    
494    (defun read-error-location (condition)
495      (let* ((finfo (car (c::source-info-current-file c::*source-info*)))
496             (file (c::file-info-name finfo))
497             (pos (c::compiler-read-error-position condition)))
498        (cond ((and (eq file :stream) *buffer-name*)
499               (make-location (list :buffer *buffer-name*)
500                              (list :offset *buffer-start-position* pos)))
501              ((and (pathnamep file) (not *buffer-name*))
502               (make-location (list :file (unix-truename file))
503                              (list :position (1+ pos))))
504              (t (break)))))
505    
506  (defun compiler-note-location (context)  (defun compiler-note-location (context)
507    (cond (context    "Derive the location of a complier message from its context.
508           (resolve-note-location  Return a `location' record, or (:error REASON) on failure."
509            *buffer-name*    (if (null context)
510            (c::compiler-error-context-file-name context)        (note-error-location)
511            (c::compiler-error-context-file-position context)        (with-struct (c::compiler-error-context- file-name
512            (reverse (c::compiler-error-context-original-source-path context))                                                 original-source
513            (c::compiler-error-context-original-source context)))                                                 original-source-path) context
514          (t          (or (locate-compiler-note file-name original-source
515           (resolve-note-location *buffer-name* nil nil nil nil))))                                    (reverse original-source-path))
516                (note-error-location)))))
517  (defgeneric resolve-note-location (buffer file-name file-position  
518                                            source-path source))  (defun note-error-location ()
519      "Pseudo-location for notes that can't be located."
520  (defmethod resolve-note-location ((b (eql nil)) (f pathname) pos path source)    (cond (*compile-file-truename*
521    (make-location           (make-location (list :file (unix-truename *compile-file-truename*))
522     `(:file ,(unix-truename f))                          (list :eof)))
523     `(:position ,(1+ (source-path-file-position path f)))))          (*buffer-name*
524             (make-location (list :buffer *buffer-name*)
 (defmethod resolve-note-location ((b string) (f (eql :stream)) pos path source)  
   (make-location  
    `(:buffer ,b)  
    `(:position ,(+ *buffer-start-position*  
                    (source-path-string-position path *buffer-substring*)))))  
   
 (defmethod resolve-note-location (b (f (eql :lisp)) pos path (source string))  
   (make-location  
    `(:source-form ,source)  
    `(:position 1)))  
   
 (defmethod resolve-note-location (buffer  
                                   (file (eql nil))  
                                   (pos (eql nil))  
                                   (path (eql nil))  
                                   (source (eql nil)))  
   (cond (buffer  
          (make-location (list :buffer buffer)  
525                          (list :position *buffer-start-position*)))                          (list :position *buffer-start-position*)))
526          (*compile-file-truename*          (t (list :error "No error location available."))))
          (make-location (list :file (namestring *compile-file-truename*))  
                         (list :position 0)))  
         (*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))  
     (handler-bind ((c::compiler-error #'handle-notification-condition)  
                    (c::style-warning  #'handle-notification-condition)  
                    (c::warning        #'handle-notification-condition))  
       ,@body)))  
527    
528  (defmethod compile-file-for-emacs (filename load-p)  (defun locate-compiler-note (file source source-path)
529    (clear-xref-info filename)    (cond ((and (eq file :stream) *buffer-name*)
530    (with-compilation-hooks ()           ;; Compiling from a buffer
531      (let ((*buffer-name* nil)           (make-location (list :buffer *buffer-name*)
532            (*compile-filename* filename))                          (list :offset *buffer-start-position*
533          (compile-file filename :load load-p))))                                (source-path-string-position
534                                   source-path *buffer-substring*))))
535            ((and (pathnamep file) (null *buffer-name*))
536             ;; Compiling from a file
537             (make-location (list :file (unix-truename file))
538                            (list :position (1+ (source-path-file-position
539                                                 source-path file)))))
540            ((and (eq file :lisp) (stringp source))
541             ;; No location known, but we have the source form.
542             ;; XXX How is this case triggered?  -luke (16/May/2004)
543             ;; This can happen if the compiler needs to expand a macro
544             ;; but the macro-expander is not yet compiled.  Calling the
545             ;; (interpreted) macro-expander triggers IR1 conversion of
546             ;; the lambda expression for the expander and invokes the
547             ;; compiler recursively.
548             (make-location (list :source-form source)
549                            (list :position 1)))))
550    
551  (defmethod compile-string-for-emacs (string &key buffer position)  (defun unix-truename (pathname)
552    (with-compilation-hooks ()    (ext:unix-namestring (truename pathname)))
     (let ((*package* *buffer-package*)  
           (*compile-filename* nil)  
           (*buffer-name* buffer)  
           (*buffer-start-position* position)  
           (*buffer-substring* string))  
       (with-input-from-string (stream string)  
         (ext:compile-from-stream  
          stream  
          :source-info `(:emacs-buffer ,buffer  
                         :emacs-buffer-offset ,position  
                         :emacs-buffer-string ,string))))))  
553    
554    
555  ;;;; XREF  ;;;; XREF
556    ;;;
557    ;;; Cross-reference support is based on the standard CMUCL `XREF'
558    ;;; package. This package has some caveats: XREF information is
559    ;;; recorded during compilation and not preserved in fasl files, and
560    ;;; XREF recording is disabled by default. Redefining functions can
561    ;;; also cause duplicate references to accumulate, but
562    ;;; `swank-compile-file' will automatically clear out any old records
563    ;;; from the same filename.
564    ;;;
565    ;;; To enable XREF recording, set `c:*record-xref-info*' to true. To
566    ;;; clear out the XREF database call `xref:init-xref-database'.
567    
568  (defun lookup-xrefs (finder name)  (defmacro defxref (name function)
569    (xref-results-for-emacs (funcall finder (from-string name))))    `(defimplementation ,name (name)
570        (xref-results (,function name))))
571  (defslimefun who-calls (function-name)  
572    "Return the places where FUNCTION-NAME is called."  (defxref who-calls      xref:who-calls)
573    (lookup-xrefs #'xref:who-calls function-name))  (defxref who-references xref:who-references)
574    (defxref who-binds      xref:who-binds)
575  (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))  
576    
577    ;;; More types of XREF information were added since 18e:
578    ;;;
579  #+cmu19  #+cmu19
580  (progn  (progn
581    (defslimefun who-macroexpands (macro)    (defxref who-macroexpands xref:who-macroexpands)
582      "Return the places where MACRO is expanded."    ;; XXX
583      (lookup-xrefs #'xref:who-macroexpands macro))    (defimplementation who-specializes (symbol)
584        (let* ((methods (xref::who-specializes (find-class symbol)))
585    (defslimefun who-specializes (class)             (locations (mapcar #'method-location methods)))
586      "Return the methods with specializers for CLASS."        (mapcar #'list methods locations))))
587      (let* ((methods (xref::who-specializes (find-class (from-string class))))  
588             (locations (mapcar #'method-source-location methods)))  (defun xref-results (contexts)
589        (group-xrefs (mapcar (lambda (m l)    (mapcar (lambda (xref)
590                               (cons (let ((*print-pretty* nil))              (list (xref:xref-context-name xref)
591                                       (to-string m))                    (resolve-xref-location xref)))
592                                     l))            contexts))
                            methods locations))))  
   )  
593    
594  (defun resolve-xref-location (xref)  (defun resolve-xref-location (xref)
595    (let ((name (xref:xref-context-name xref))    (let ((name (xref:xref-context-name xref))
# Line 363  the error-context redundant." Line 603  the error-context redundant."
603             (make-location (list :file (unix-truename file))             (make-location (list :file (unix-truename file))
604                            (list :function-name (string name))))                            (list :function-name (string name))))
605            (t            (t
606             `(:error ,(format nil "Unkown source location: ~S ~S ~S "             `(:error ,(format nil "Unknown source location: ~S ~S ~S "
607                               name file source-path))))))                               name file source-path))))))
608    
   
 (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))))  
   
609  (defun clear-xref-info (namestring)  (defun clear-xref-info (namestring)
610    "Clear XREF notes pertaining to FILENAME.    "Clear XREF notes pertaining to NAMESTRING.
611  This is a workaround for a CMUCL bug: XREF records are cumulative."  This is a workaround for a CMUCL bug: XREF records are cumulative."
612    (let ((filename (parse-namestring namestring)))    (when c:*record-xref-info*
613      (when c:*record-xref-info*      (let ((filename (truename namestring)))
614        (dolist (db (list xref::*who-calls*        (dolist (db (list xref::*who-calls*
615                          #+cmu19 xref::*who-is-called*                          #+cmu19 xref::*who-is-called*
616                          #+cmu19 xref::*who-macroexpands*                          #+cmu19 xref::*who-macroexpands*
# Line 415  This is a workaround for a CMUCL bug: XR Line 618  This is a workaround for a CMUCL bug: XR
618                          xref::*who-binds*                          xref::*who-binds*
619                          xref::*who-sets*))                          xref::*who-sets*))
620          (maphash (lambda (target contexts)          (maphash (lambda (target contexts)
621                       ;; XXX update during traversal?
622                     (setf (gethash target db)                     (setf (gethash target db)
623                           (delete-if                           (delete filename contexts
624                            (lambda (ctx)                                   :key #'xref:xref-context-file
625                              (xref-context-derived-from-p ctx filename))                                   :test #'equalp)))
                           contexts)))  
626                   db)))))                   db)))))
627    
 (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)))  
   
 (defun unix-truename (pathname)  
   (ext:unix-namestring (truename pathname)))  
   
628    
629  ;;;; Find callers and callees  ;;;; Find callers and callees
630    ;;;
631  ;;; Find callers and callees by looking at the constant pool of  ;;; Find callers and callees by looking at the constant pool of
632  ;;; compiled code objects.  We assume every fdefn object in the  ;;; compiled code objects.  We assume every fdefn object in the
633  ;;; constant pool corresponds to a call to that function.  A better  ;;; constant pool corresponds to a call to that function.  A better
634  ;;; strategy would be to use the disassembler to find actual  ;;; strategy would be to use the disassembler to find actual
635  ;;; call-sites.  ;;; call-sites.
636    
637  (declaim (inline map-code-constants))  (labels ((make-stack () (make-array 100 :fill-pointer 0 :adjustable t))
638  (defun map-code-constants (code fn)           (map-cpool (code fun)
639    "Call FN for each constant in CODE's constant pool."             (declare (type kernel:code-component code) (type function fun))
640    (check-type code kernel:code-component)             (loop for i from vm:code-constants-offset
641    (loop for i from vm:code-constants-offset below (kernel:get-header-data code)                   below (kernel:get-header-data code)
642          do (funcall fn (kernel:code-header-ref code i))))                   do (funcall fun (kernel:code-header-ref code i))))
643    
644  (defun function-callees (function)           (callees (fun)
645    "Return FUNCTION's callees as a list of functions."             (let ((callees (make-stack)))
646    (let ((callees '()))               (map-cpool (vm::find-code-object fun)
647      (map-code-constants                          (lambda (o)
648       (vm::find-code-object function)                            (when (kernel:fdefn-p o)
649       (lambda (obj)                              (vector-push-extend (kernel:fdefn-function o)
650         (when (kernel:fdefn-p obj)                                                  callees))))
651           (push (kernel:fdefn-function obj) callees))))               (coerce callees 'list)))
652      callees))  
653             (callers (fun)
654  (declaim (ext:maybe-inline map-allocated-code-components))             (declare (function fun))
655  (defun map-allocated-code-components (spaces fn)             (let ((callers (make-stack)))
656    "Call FN for each allocated code component in one of SPACES.  FN               (ext:gc :full t)
657  receives the object as argument.  SPACES should be a list of the               ;; scan :dynamic first to avoid the need for even more gcing
658  symbols :dynamic, :static, or :read-only."               (dolist (space '(:dynamic :read-only :static))
659    (dolist (space spaces)                 (vm::map-allocated-objects
660      (declare (inline vm::map-allocated-objects))                  (lambda (obj header size)
661      (vm::map-allocated-objects                    (declare (type fixnum header) (ignore size))
662       (lambda (obj header size)                    (when (= vm:code-header-type header)
663         (declare (type fixnum size) (ignore size))                      (map-cpool obj
664         (when (= vm:code-header-type header)                                 (lambda (c)
665           (funcall fn obj)))                                   (when (and (kernel:fdefn-p c)
666       space)))                                              (eq (kernel:fdefn-function c) fun))
667                                       (vector-push-extend obj callers))))))
668  (declaim (ext:maybe-inline map-caller-code-components))                  space)
669  (defun map-caller-code-components (function spaces fn)                 (ext:gc))
670    "Call FN for each code component with a fdefn for FUNCTION in its               (coerce callers 'list)))
671  constant pool."  
672    (let ((function (coerce function 'function)))           (entry-points (code)
673      (declare (inline map-allocated-code-components))             (loop for entry = (kernel:%code-entry-points code)
674      (map-allocated-code-components                   then (kernel::%function-next entry)
675       spaces                   while entry
676       (lambda (obj)                   collect entry))
677         (map-code-constants  
678          obj           (guess-main-entry-point (entry-points)
679          (lambda (constant)             (or (find-if (lambda (fun)
680            (when (and (kernel:fdefn-p constant)                            (ext:valid-function-name-p
681                       (eq (kernel:fdefn-function constant)                             (kernel:%function-name fun)))
682                           function))                          entry-points)
683              (funcall fn obj))))))))                 (car entry-points)))
684    
685  (defun function-callers (function &optional (spaces '(:read-only :static           (fun-dspec (fun)
686                                                        :dynamic)))             (list (kernel:%function-name fun) (function-location fun)))
687    "Return FUNCTION's callers.  The result is a list of code-objects."  
688    (let ((referrers '()))           (code-dspec (code)
689      (declare (inline map-caller-code-components))             (let ((eps (entry-points code))
690      (ext:gc :full t)                   (di (kernel:%code-debug-info code)))
691      (map-caller-code-components function spaces               (cond (eps (fun-dspec (guess-main-entry-point eps)))
692                                  (lambda (code) (push code referrers)))                     (di (list (c::debug-info-name di)
693      referrers))                               (debug-info-function-name-location di)))
694                       (t (list (princ-to-string code)
695  (defun debug-info-definitions (debug-info)                              `(:error "No src-loc available")))))))
696    "Return the defintions for a debug-info.  This should only be used    (declare (inline map-cpool))
697  for code-object without entry points, i.e., byte compiled  
698  code (are theree others?)"    (defimplementation list-callers (symbol)
699    ;; This mess has only been tested with #'ext::skip-whitespace, a      (mapcar #'code-dspec (callers (coerce symbol 'function) )))
700    ;; byte-compiled caller of #'read-char .  
701    (check-type debug-info (and (not c::compiled-debug-info) c::debug-info))    (defimplementation list-callees (symbol)
702    (let ((name (c::debug-info-name debug-info))      (mapcar #'fun-dspec (callees symbol))))
703          (source (c::debug-info-source debug-info)))  
704      (destructuring-bind (first) source  (defun test-list-callers (count)
705        (ecase (c::debug-source-from first)    (let ((funsyms '()))
706          (:file      (do-all-symbols (s)
707           (list        (when (and (fboundp s)
708            (cons name                   (functionp (symbol-function s))
709                  (make-location                   (not (macro-function s))
710                   (list :file (unix-truename (c::debug-source-name first)))                   (not (special-operator-p s)))
711                   (list :function-name name)))))))))          (push s funsyms)))
712        (let ((len (length funsyms)))
713  (defun code-component-entry-points (code)        (dotimes (i count)
714    "Return a list ((NAME . LOCATION) ...) of function definitons for          (let ((sym (nth (random len) funsyms)))
715  the code omponent CODE."            (format t "~s -> ~a~%" sym (mapcar #'car (list-callers sym))))))))
716    (delete-duplicates  
717     (loop for e = (kernel:%code-entry-points code)  ;; (test-list-callers 100)
          then (kernel::%function-next e)  
          while e  
          collect (cons (to-string (kernel:%function-name e))  
                        (function-source-location e)))  
    :test #'equal))  
   
 (defslimefun list-callers (symbol-name)  
   "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."  
   (let ((components (function-callers (from-string symbol-name)))  
         (xrefs '()))  
     (dolist (code components)  
       (let* ((entry (kernel:%code-entry-points code))  
              (defs (if entry  
                        (code-component-entry-points code)  
                        ;; byte compiled stuff  
                        (debug-info-definitions  
                         (kernel:%code-debug-info code)))))  
         (setq xrefs (nconc defs xrefs))))  
     (group-xrefs xrefs)))  
   
   
 (defslimefun list-callees (symbol-name)  
   (let ((fns (function-callees (from-string symbol-name))))  
     (group-xrefs (mapcar (lambda (fn)  
                            (cons (to-string (kernel:%function-name fn))  
                                  (function-source-location fn)))  
                          fns))))  
718    
719  ;;;; Definitions  
720    ;;;; Resolving source locations
721    ;;;
722    ;;; Our mission here is to "resolve" references to code locations into
723    ;;; actual file/buffer names and character positions. The references
724    ;;; we work from come out of the compiler's statically-generated debug
725    ;;; information, such as `code-location''s and `debug-source''s. For
726    ;;; more details, see the "Debugger Programmer's Interface" section of
727    ;;; the CMUCL manual.
728    ;;;
729    ;;; The first step is usually to find the corresponding "source-path"
730    ;;; for the location. Once we have the source-path we can pull up the
731    ;;; source file and `READ' our way through to the right position. The
732    ;;; main source-code groveling work is done in
733    ;;; `swank-source-path-parser.lisp'.
734    
735  (defvar *debug-definition-finding* t  (defvar *debug-definition-finding* nil
736    "When true don't handle errors while looking for definitions.    "When true don't handle errors while looking for definitions.
737  This is useful when debugging the definition-finding code.")  This is useful when debugging the definition-finding code.")
738    
739    (defvar *source-snippet-size* 256
740      "Maximum number of characters in a snippet of source code.
741    Snippets at the beginning of definitions are used to tell Emacs what
742    the definitions looks like, so that it can accurately find them by
743    text search.")
744    
745  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
746    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY and return the source-location it returns.
747  returned by BODY or if an error occurs a description of the error.  If an error occurs and `*debug-definition-finding*' is false, then
748  The second return value is the condition or nil."  return an error pseudo-location.
749    
750    The second return value is NIL if no error occurs, otherwise it is the
751    condition object."
752    `(flet ((body () ,@body))    `(flet ((body () ,@body))
753      (if *debug-definition-finding*      (if *debug-definition-finding*
754          (body)          (body)
755          (handler-case (values (progn ,@body) nil)          (handler-case (values (progn ,@body) nil)
756            (error (c) (values (list :error (princ-to-string c)) c))))))            (error (c) (values `(:error ,(trim-whitespace (princ-to-string c)))
757                                 c))))))
758    
759    (defun trim-whitespace (string)
760      (string-trim #(#\newline #\space #\tab) string))
761    
762    (defun code-location-source-location (code-location)
763      "Safe wrapper around `code-location-from-source-location'."
764      (safe-definition-finding
765       (source-location-from-code-location code-location)))
766    
767    (defun source-location-from-code-location (code-location)
768      "Return the source location for CODE-LOCATION."
769      (let ((debug-fun (di:code-location-debug-function code-location)))
770        (when (di::bogus-debug-function-p debug-fun)
771          ;; Those lousy cheapskates! They've put in a bogus debug source
772          ;; because the code was compiled at a low debug setting.
773          (error "Bogus debug function: ~A" debug-fun)))
774      (let* ((debug-source (di:code-location-debug-source code-location))
775             (from (di:debug-source-from debug-source))
776             (name (di:debug-source-name debug-source)))
777        (ecase from
778          (:file
779           (location-in-file name code-location debug-source))
780          (:stream
781           (location-in-stream code-location debug-source))
782          (:lisp
783           ;; The location comes from a form passed to `compile'.
784           ;; The best we can do is return the form itself for printing.
785           (make-location
786            (list :source-form (with-output-to-string (*standard-output*)
787                                 (debug::print-code-location-source-form
788                                  code-location 100 t)))
789            (list :position 1))))))
790    
791    (defun location-in-file (filename code-location debug-source)
792      "Resolve the source location for CODE-LOCATION in FILENAME."
793      (let* ((code-date (di:debug-source-created debug-source))
794             (source-code (get-source-code filename code-date)))
795        (with-input-from-string (s source-code)
796          (make-location (list :file (unix-truename filename))
797                         (list :position (1+ (code-location-stream-position
798                                              code-location s)))
799                         `(:snippet ,(read-snippet s))))))
800    
801    (defun location-in-stream (code-location debug-source)
802      "Resolve the source location for a CODE-LOCATION from a stream.
803    This only succeeds if the code was compiled from an Emacs buffer."
804      (unless (debug-source-info-from-emacs-buffer-p debug-source)
805        (error "The code is compiled from a non-SLIME stream."))
806      (let* ((info (c::debug-source-info debug-source))
807             (string (getf info :emacs-buffer-string))
808             (position (code-location-string-offset
809                        code-location
810                        string)))
811        (make-location
812         (list :buffer (getf info :emacs-buffer))
813         (list :offset (getf info :emacs-buffer-offset) position)
814         (list :snippet (with-input-from-string (s string)
815                          (file-position s position)
816                          (read-snippet s))))))
817    
818    ;;;;; Function-name locations
819    ;;;
820    (defun debug-info-function-name-location (debug-info)
821      "Return a function-name source-location for DEBUG-INFO.
822    Function-name source-locations are a fallback for when precise
823    positions aren't available."
824      (with-struct (c::debug-info- (fname name) source) debug-info
825        (with-struct (c::debug-source- info from name) (car source)
826          (ecase from
827            (:file
828             (make-location (list :file (namestring (truename name)))
829                            (list :function-name (string fname))))
830            (:stream
831             (assert (debug-source-info-from-emacs-buffer-p (car source)))
832             (make-location (list :buffer (getf info :emacs-buffer))
833                            (list :function-name (string fname))))
834            (:lisp
835             (make-location (list :source-form (princ-to-string (aref name 0)))
836                            (list :position 1)))))))
837    
838    (defun debug-source-info-from-emacs-buffer-p (debug-source)
839      "Does the `info' slot of DEBUG-SOURCE contain an Emacs buffer location?
840    This is true for functions that were compiled directly from buffers."
841      (info-from-emacs-buffer-p (c::debug-source-info debug-source)))
842    
843    (defun info-from-emacs-buffer-p (info)
844      (and info
845           (consp info)
846           (eq :emacs-buffer (car info))))
847    
848    
849    ;;;;; Groveling source-code for positions
850    
851    (defun code-location-stream-position (code-location stream)
852      "Return the byte offset of CODE-LOCATION in STREAM.  Extract the
853    toplevel-form-number and form-number from CODE-LOCATION and use that
854    to find the position of the corresponding form.
855    
856    Finish with STREAM positioned at the start of the code location."
857      (let* ((location (debug::maybe-block-start-location code-location))
858             (tlf-offset (di:code-location-top-level-form-offset location))
859             (form-number (di:code-location-form-number location)))
860        (let ((pos (form-number-stream-position tlf-offset form-number stream)))
861          (file-position stream pos)
862          pos)))
863    
864    (defun form-number-stream-position (tlf-number form-number stream)
865      "Return the starting character position of a form in STREAM.
866    TLF-NUMBER is the top-level-form number.
867    FORM-NUMBER is an index into a source-path table for the TLF."
868      (multiple-value-bind (tlf position-map) (read-source-form tlf-number stream)
869        (let* ((path-table (di:form-number-translations tlf 0))
870               (source-path
871                (if (<= (length path-table) form-number) ; source out of sync?
872                    (list 0)                ; should probably signal a condition
873                    (reverse (cdr (aref path-table form-number))))))
874          (source-path-source-position source-path tlf position-map))))
875    
876    (defun code-location-string-offset (code-location string)
877      "Return the byte offset of CODE-LOCATION in STRING.
878    See CODE-LOCATION-STREAM-POSITION."
879      (with-input-from-string (s string)
880        (code-location-stream-position code-location s)))
881    
882    
883    ;;;; Finding definitions
884    
885    ;;; There are a great many different types of definition for us to
886    ;;; find. We search for definitions of every kind and return them in a
887    ;;; list.
888    
889    (defimplementation find-definitions (name)
890      (append (function-definitions name)
891              (setf-definitions name)
892              (variable-definitions name)
893              (class-definitions name)
894              (type-definitions name)
895              (compiler-macro-definitions name)
896              (source-transform-definitions name)
897              (function-info-definitions name)
898              (ir1-translator-definitions name)))
899    
900    ;;;;; Functions, macros, generic functions, methods
901    ;;;
902    ;;; We make extensive use of the compile-time debug information that
903    ;;; CMUCL records, in particular "debug functions" and "code
904    ;;; locations." Refer to the "Debugger Programmer's Interface" section
905    ;;; of the CMUCL manual for more details.
906    
907    (defun function-definitions (name)
908      "Return definitions for NAME in the \"function namespace\", i.e.,
909    regular functions, generic functions, methods and macros.
910    NAME can any valid function name (e.g, (setf car))."
911      (let ((macro?    (and (symbolp name) (macro-function name)))
912            (special?  (and (symbolp name) (special-operator-p name)))
913            (function? (and (ext:valid-function-name-p name)
914                            (ext:info :function :definition name)
915                            (if (symbolp name) (fboundp name) t))))
916        (cond (macro?
917               (list `((defmacro ,name)
918                       ,(function-location (macro-function name)))))
919              (special?
920               (list `((:special-operator ,name)
921                       (:error ,(format nil "Special operator: ~S" name)))))
922              (function?
923               (let ((function (fdefinition name)))
924                 (if (genericp function)
925                     (generic-function-definitions name function)
926                     (list (list `(function ,name)
927                                 (function-location function)))))))))
928    
929    ;;;;;; Ordinary (non-generic/macro/special) functions
930    ;;;
931    ;;; First we test if FUNCTION is a closure created by defstruct, and
932    ;;; if so extract the defstruct-description (`dd') from the closure
933    ;;; and find the constructor for the struct.  Defstruct creates a
934    ;;; defun for the default constructor and we use that as an
935    ;;; approximation to the source location of the defstruct.
936    ;;;
937    ;;; For an ordinary function we return the source location of the
938    ;;; first code-location we find.
939    ;;;
940    (defun function-location (function)
941      "Return the source location for FUNCTION."
942      (cond ((struct-closure-p function)
943             (struct-closure-location function))
944            ((c::byte-function-or-closure-p function)
945             (byte-function-location function))
946            (t
947             (compiled-function-location function))))
948    
949    (defun compiled-function-location (function)
950      "Return the location of a regular compiled function."
951      (multiple-value-bind (code-location error)
952          (safe-definition-finding (function-first-code-location function))
953        (cond (error (list :error (princ-to-string error)))
954              (t (code-location-source-location code-location)))))
955    
956  (defun function-first-code-location (function)  (defun function-first-code-location (function)
957      "Return the first code-location we can find for FUNCTION."
958    (and (function-has-debug-function-p function)    (and (function-has-debug-function-p function)
959         (di:debug-function-start-location         (di:debug-function-start-location
960          (di:function-debug-function function))))          (di:function-debug-function function))))
# Line 580  The second return value is the condition Line 967  The second return value is the condition
967             (vm::find-code-object function))             (vm::find-code-object function))
968         (not (eq closure function))))         (not (eq closure function))))
969    
970    (defun byte-function-location (fun)
971      "Return the location of the byte-compiled function FUN."
972      (etypecase fun
973        ((or c::hairy-byte-function c::simple-byte-function)
974         (let* ((di (kernel:%code-debug-info (c::byte-function-component fun))))
975           (if di
976               (debug-info-function-name-location di)
977               `(:error
978                 ,(format nil "Byte-function without debug-info: ~a" fun)))))
979        (c::byte-closure
980         (byte-function-location (c::byte-closure-function fun)))))
981    
982    ;;; Here we deal with structure accessors. Note that `dd' is a
983    ;;; "defstruct descriptor" structure in CMUCL. A `dd' describes a
984    ;;; `defstruct''d structure.
985    
986  (defun struct-closure-p (function)  (defun struct-closure-p (function)
987      "Is FUNCTION a closure created by defstruct?"
988    (or (function-code-object= function #'kernel::structure-slot-accessor)    (or (function-code-object= function #'kernel::structure-slot-accessor)
989        (function-code-object= function #'kernel::structure-slot-setter)        (function-code-object= function #'kernel::structure-slot-setter)
990        (function-code-object= function #'kernel::%defstruct)))        (function-code-object= function #'kernel::%defstruct)))
991    
992    (defun struct-closure-location (function)
993      "Return the location of the structure that FUNCTION belongs to."
994      (assert (struct-closure-p function))
995      (safe-definition-finding
996        (dd-location (struct-closure-dd function))))
997    
998  (defun struct-closure-dd (function)  (defun struct-closure-dd (function)
999      "Return the defstruct-definition (dd) of FUNCTION."
1000    (assert (= (kernel:get-type function) vm:closure-header-type))    (assert (= (kernel:get-type function) vm:closure-header-type))
1001    (flet ((find-layout (function)    (flet ((find-layout (function)
1002             (sys:find-if-in-closure             (sys:find-if-in-closure
# Line 597  The second return value is the condition Line 1008  The second return value is the condition
1008                    (return-from find-layout value))))                    (return-from find-layout value))))
1009              function)))              function)))
1010      (kernel:layout-info (find-layout function))))      (kernel:layout-info (find-layout function))))
1011    
1012  (defun dd-source-location (dd)  (defun dd-location (dd)
1013      "Return the location of a `defstruct'."
1014      ;; Find the location in a constructor.
1015      (function-location (struct-constructor dd)))
1016    
1017    (defun struct-constructor (dd)
1018      "Return a constructor function from a defstruct definition.
1019    Signal an error if no constructor can be found."
1020    (let ((constructor (or (kernel:dd-default-constructor dd)    (let ((constructor (or (kernel:dd-default-constructor dd)
1021                           (car (kernel::dd-constructors dd)))))                           (car (kernel::dd-constructors dd)))))
1022      (when (or (not constructor) (and (consp constructor)      (when (or (null constructor)
1023                                       (not (car constructor))))                (and (consp constructor) (null (car constructor))))
1024        (error "Cannot locate struct without constructor: ~S"        (error "Cannot find structure's constructor: ~S"
1025               (kernel::dd-name dd)))               (kernel::dd-name dd)))
1026      (function-source-location      (coerce (if (consp constructor) (first constructor) constructor)
1027       (coerce (if (consp constructor) (car constructor) constructor)              'function)))
1028               'function))))  
1029    ;;;;;; Generic functions and methods
1030    
1031    (defun generic-function-definitions (name function)
1032      "Return the definitions of a generic function and its methods."
1033      (cons (list `(defgeneric ,name) (gf-location function))
1034            (gf-method-definitions function)))
1035    
1036    (defun gf-location (gf)
1037      "Return the location of the generic function GF."
1038      (definition-source-location gf (pcl::generic-function-name gf)))
1039    
1040    (defun gf-method-definitions (gf)
1041      "Return the locations of all methods of the generic function GF."
1042      (mapcar #'method-definition (pcl::generic-function-methods gf)))
1043    
1044    (defun method-definition (method)
1045      (list (method-dspec method)
1046            (method-location method)))
1047    
1048    (defun method-dspec (method)
1049      "Return a human-readable \"definition specifier\" for METHOD."
1050      (let* ((gf (pcl:method-generic-function method))
1051             (name (pcl:generic-function-name gf))
1052             (specializers (pcl:method-specializers method))
1053             (qualifiers (pcl:method-qualifiers method)))
1054        `(method ,name ,@qualifiers ,(pcl::unparse-specializers specializers))))
1055    
1056    ;; XXX maybe special case setters/getters
1057    (defun method-location (method)
1058      (function-location (or (pcl::method-fast-function method)
1059                             (pcl:method-function method))))
1060    
1061  (defun genericp (fn)  (defun genericp (fn)
1062    (typep fn 'generic-function))    (typep fn 'generic-function))
1063    
1064  (defun gf-definition-location (gf)  ;;;;;; Types and classes
1065    (flet ((guess-source-file (faslfile)  
1066             (unix-truename  (defun type-definitions (name)
1067              (merge-pathnames (make-pathname :type "lisp")    "Return `deftype' locations for type NAME."
1068                               faslfile))))    (maybe-make-definition (ext:info :type :expander name) 'deftype name))
1069      (let ((def-source (pcl::definition-source gf))  
1070            (name (string (pcl:generic-function-name gf))))  (defun maybe-make-definition (function kind name)
1071        (etypecase def-source    "If FUNCTION is non-nil then return its definition location."
1072          (pathname (make-location    (if function
1073                     `(:file ,(guess-source-file def-source))        (list (list `(,kind ,name) (function-location function)))))
1074                     `(:function-name ,name)))  
1075          (cons  (defun class-definitions (name)
1076           (destructuring-bind ((dg name) pathname) def-source    "Return the definition locations for the class called NAME."
1077             (declare (ignore dg))    (if (symbolp name)
1078             (etypecase pathname        (let ((class (kernel::find-class name nil)))
1079               (pathname          (etypecase class
1080                (make-location `(:file ,(guess-source-file pathname))            (null '())
1081                               `(:function-name ,(string name)))))))))))            (kernel::structure-class
1082               (list (list `(defstruct ,name) (dd-location (find-dd name)))))
1083  (defun method-source-location (method)            #+(or)
1084    (function-source-location (or (pcl::method-fast-function method)            (conditions::condition-class
1085                                  (pcl:method-function method))))             (list (list `(define-condition ,name)
1086                           (condition-class-location class))))
1087  (defun gf-method-locations (gf)            (kernel::standard-class
1088    (let ((ms (pcl::generic-function-methods gf)))             (list (list `(defclass ,name)
1089      (mapcar #'method-source-location ms)))                         (class-location (find-class name)))))
1090              ((or kernel::built-in-class
1091  (defun gf-source-locations (gf)                 conditions::condition-class
1092    (list* (gf-definition-location gf)                 kernel:funcallable-structure-class)
1093           (gf-method-locations gf)))             (list (list `(kernel::define-type-class ,name)
1094                           `(:error
1095  (defun function-source-locations (function)                           ,(format nil "No source info for ~A" name)))))))))
1096    "Return a list of source locations for FUNCTION."  
1097    ;; First test if FUNCTION is a closure created by defstruct; if so  (defun class-location (class)
1098    ;; extract the defstruct-description (dd) from the closure and find    "Return the `defclass' location for CLASS."
1099    ;; the constructor for the struct.  Defstruct creates a defun for    (definition-source-location class (pcl:class-name class)))
1100    ;; the default constructor and we use that as an approximation to  
1101    ;; the source location of the defstruct.  (defun find-dd (name)
1102    ;;    "Find the defstruct-definition by the name of its structure-class."
1103    ;; For an ordinary function we return the source location of the    (let ((layout (ext:info :type :compiler-layout name)))
1104    ;; first code-location we find.      (if layout
1105    (cond ((struct-closure-p function)          (kernel:layout-info layout))))
1106           (list  
1107            (safe-definition-finding  (defun condition-class-location (class)
1108             (dd-source-location (struct-closure-dd function)))))    (let ((slots (conditions::condition-class-slots class))
1109          ((genericp function)          (name (conditions::condition-class-name class)))
1110           (gf-source-locations function))      (cond ((null slots)
1111          (t             `(:error ,(format nil "No location info for condition: ~A" name)))
1112           (list            (t
1113            (multiple-value-bind (code-location error)             ;; Find the class via one of its slot-reader methods.
1114                (safe-definition-finding (function-first-code-location function))             (let* ((slot (first slots))
1115              (cond (error (list :error (princ-to-string error)))                    (gf (fdefinition
1116                    (t (code-location-source-location code-location))))))))                         (first (conditions::condition-slot-readers slot)))))
1117                 (method-location
1118  (defun function-source-location (function)                (first
1119    (destructuring-bind (first) (function-source-locations function)                 (pcl:compute-applicable-methods-using-classes
1120      first))                  gf (list (find-class name))))))))))
1121    
1122  (defslimefun find-function-locations (symbol-name)  (defun make-name-in-file-location (file string)
1123    "Return a list of source-locations for SYMBOL-NAME's functions."    (multiple-value-bind (filename c)
1124    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)        (ignore-errors
1125      (cond ((not foundp)          (unix-truename (merge-pathnames (make-pathname :type "lisp")
1126             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))                                          file)))
1127            ((macro-function symbol)      (cond (filename (make-location `(:file ,filename)
1128             (function-source-locations (macro-function symbol)))                                     `(:function-name ,(string string))))
1129            ((special-operator-p symbol)            (t (list :error (princ-to-string c))))))
1130             (list (list :error (format nil "~A is a special-operator" symbol))))  
1131            ((fboundp symbol)  (defun source-location-form-numbers (location)
1132             (function-source-locations (coerce symbol 'function)))    (c::decode-form-numbers (c::form-numbers-form-numbers location)))
1133            (t (list (list :error  
1134                           (format nil "Symbol not fbound: ~A" symbol-name))))  (defun source-location-tlf-number (location)
1135            )))    (nth-value 0 (source-location-form-numbers location)))
1136    
1137    (defun source-location-form-number (location)
1138      (nth-value 1 (source-location-form-numbers location)))
1139    
1140    (defun resolve-file-source-location (location)
1141      (let ((filename (c::file-source-location-pathname location))
1142            (tlf-number (source-location-tlf-number location))
1143            (form-number (source-location-form-number location)))
1144        (with-open-file (s filename)
1145          (let ((pos (form-number-stream-position tlf-number form-number s)))
1146            (make-location `(:file ,(unix-truename filename))
1147                           `(:position ,(1+ pos)))))))
1148    
1149    (defun resolve-stream-source-location (location)
1150      (let ((info (c::stream-source-location-user-info location))
1151            (tlf-number (source-location-tlf-number location))
1152            (form-number (source-location-form-number location)))
1153        ;; XXX duplication in frame-source-location
1154        (assert (info-from-emacs-buffer-p info))
1155        (destructuring-bind (&key emacs-buffer emacs-buffer-string
1156                                  emacs-buffer-offset) info
1157          (with-input-from-string (s emacs-buffer-string)
1158            (let ((pos (form-number-stream-position tlf-number form-number s)))
1159              (make-location `(:buffer ,emacs-buffer)
1160                             `(:offset ,emacs-buffer-offset ,pos)))))))
1161    
1162    ;; XXX predicates for 18e backward compatibilty.  Remove them when
1163    ;; we're 19a only.
1164    (defun file-source-location-p (object)
1165      (when (fboundp 'c::file-source-location-p)
1166        (c::file-source-location-p object)))
1167    
1168    (defun stream-source-location-p (object)
1169      (when (fboundp 'c::stream-source-location-p)
1170        (c::stream-source-location-p object)))
1171    
1172    (defun source-location-p (object)
1173      (or (file-source-location-p object)
1174          (stream-source-location-p object)))
1175    
1176    (defun resolve-source-location (location)
1177      (etypecase location
1178        ((satisfies file-source-location-p)
1179         (resolve-file-source-location location))
1180        ((satisfies stream-source-location-p)
1181         (resolve-stream-source-location location))))
1182    
1183    (defun definition-source-location (object name)
1184      (let ((source (pcl::definition-source object)))
1185        (etypecase source
1186          (null
1187           `(:error ,(format nil "No source info for: ~A" object)))
1188          ((satisfies source-location-p)
1189           (resolve-source-location source))
1190          (pathname
1191           (make-name-in-file-location source name))
1192          (cons
1193           (destructuring-bind ((dg name) pathname) source
1194             (declare (ignore dg))
1195             (etypecase pathname
1196               (pathname (make-name-in-file-location pathname (string name)))
1197               (null `(:error ,(format nil "Cannot resolve: ~S" source)))))))))
1198    
1199    (defun setf-definitions (name)
1200      (let ((function (or (ext:info :setf :inverse name)
1201                          (ext:info :setf :expander name)
1202                          (and (symbolp name)
1203                               (fboundp `(setf ,name))
1204                               (fdefinition `(setf ,name))))))
1205        (if function
1206            (list (list `(setf ,name)
1207                        (function-location (coerce function 'function)))))))
1208    
1209    
1210    (defun variable-location (symbol)
1211      (multiple-value-bind (location foundp)
1212          ;; XXX for 18e compatibilty. rewrite this when we drop 18e
1213          ;; support.
1214          (ignore-errors (eval `(ext:info :source-location :defvar ',symbol)))
1215        (if (and foundp location)
1216            (resolve-source-location location)
1217            `(:error ,(format nil "No source info for variable ~S" symbol)))))
1218    
1219    (defun variable-definitions (name)
1220      (if (symbolp name)
1221          (multiple-value-bind (kind recorded-p) (ext:info :variable :kind name)
1222            (if recorded-p
1223                (list (list `(variable ,kind ,name)
1224                            (variable-location name)))))))
1225    
1226    (defun compiler-macro-definitions (symbol)
1227      (maybe-make-definition (compiler-macro-function symbol)
1228                             'define-compiler-macro
1229                             symbol))
1230    
1231    (defun source-transform-definitions (name)
1232      (maybe-make-definition (ext:info :function :source-transform name)
1233                             'c:def-source-transform
1234                             name))
1235    
1236    (defun function-info-definitions (name)
1237      (let ((info (ext:info :function :info name)))
1238        (if info
1239            (append (loop for transform in (c::function-info-transforms info)
1240                          collect (list `(c:deftransform ,name
1241                                          ,(c::type-specifier
1242                                            (c::transform-type transform)))
1243                                        (function-location (c::transform-function
1244                                                            transform))))
1245                    (maybe-make-definition (c::function-info-derive-type info)
1246                                           'c::derive-type name)
1247                    (maybe-make-definition (c::function-info-optimizer info)
1248                                           'c::optimizer name)
1249                    (maybe-make-definition (c::function-info-ltn-annotate info)
1250                                           'c::ltn-annotate name)
1251                    (maybe-make-definition (c::function-info-ir2-convert info)
1252                                           'c::ir2-convert name)
1253                    (loop for template in (c::function-info-templates info)
1254                          collect (list `(c::vop ,(c::template-name template))
1255                                        (function-location
1256                                         (c::vop-info-generator-function
1257                                          template))))))))
1258    
1259    (defun ir1-translator-definitions (name)
1260      (maybe-make-definition (ext:info :function :ir1-convert name)
1261                             'c:def-ir1-translator name))
1262    
1263    
1264  ;;;; Documentation.  ;;;; Documentation.
1265    
1266  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
1267    (let ((result '()))    (let ((result '()))
1268      (flet ((doc (kind)      (flet ((doc (kind)
1269               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 701  The second return value is the condition Line 1276  The second return value is the condition
1276                     (declare (ignore kind))                     (declare (ignore kind))
1277                     (if (or (boundp symbol) recorded-p)                     (if (or (boundp symbol) recorded-p)
1278                         (doc 'variable))))                         (doc 'variable))))
1279        (maybe-push        (when (fboundp symbol)
1280         :generic-function          (maybe-push
1281         (if (and (fboundp symbol)           (cond ((macro-function symbol)     :macro)
1282                  (typep (fdefinition symbol) 'generic-function))                 ((special-operator-p symbol) :special-operator)
1283             (doc 'function)))                 ((genericp (fdefinition symbol)) :generic-function)
1284        (maybe-push                 (t :function))
1285         :function (if (and (fboundp symbol)           (doc 'function)))
                           (not (typep (fdefinition symbol) 'generic-function)))  
                      (doc 'function)))  
1286        (maybe-push        (maybe-push
1287         :setf (if (or (ext:info setf inverse symbol)         :setf (if (or (ext:info setf inverse symbol)
1288                       (ext:info setf expander symbol))                       (ext:info setf expander symbol))
# Line 734  The second return value is the condition Line 1307  The second return value is the condition
1307                         (doc nil)))                         (doc nil)))
1308        result)))        result)))
1309    
1310  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
1311    (print-description-to-string    (describe (ecase namespace
1312     (or (ext:info setf inverse (from-string symbol-name))                (:variable
1313         (ext:info setf expander (from-string symbol-name)))))                 symbol)
1314                  ((:function :generic-function)
1315  (defslimefun describe-type (symbol-name)                 (symbol-function symbol))
1316    (print-description-to-string                (:setf
1317     (kernel:values-specifier-type (from-string symbol-name))))                 (or (ext:info setf inverse symbol)
1318                       (ext:info setf expander symbol)))
1319  (defslimefun describe-class (symbol-name)                (:type
1320    (print-description-to-string (find-class (from-string symbol-name) nil)))                 (kernel:values-specifier-type symbol))
1321                  (:class
1322  (defslimefun describe-alien-type (symbol-name)                 (find-class symbol))
1323    (let ((name (from-string symbol-name)))                (:alien-struct
1324      (ecase (ext:info :alien-type :kind name)                 (ext:info :alien-type :struct symbol))
1325        (:primitive                (:alien-union
1326         (print-description-to-string                 (ext:info :alien-type :union symbol))
1327          (let ((alien::*values-type-okay* t))                (:alien-enum
1328            (funcall (ext:info :alien-type :translator name) (list name)))))                 (ext:info :alien-type :enum symbol))
1329        ((:defined)                (:alien-type
1330         (print-description-to-string (ext:info :alien-type :definition name)))                 (ecase (ext:info :alien-type :kind symbol)
1331        (:unknown                   (:primitive
1332         (format nil "Unkown alien type: ~A" symbol-name)))))                    (let ((alien::*values-type-okay* t))
1333                        (funcall (ext:info :alien-type :translator symbol)
1334  (defmacro %describe-alien (symbol-name namespace)                               (list symbol))))
1335    `(print-description-to-string                   ((:defined)
1336      (ext:info :alien-type ,namespace (from-string ,symbol-name))))                    (ext:info :alien-type :definition symbol))
1337                     (:unknown :unkown))))))
1338  (defslimefun describe-alien-struct (symbol-name)  
1339    (%describe-alien symbol-name :struct))  ;;;;; Argument lists
1340    
1341  (defslimefun describe-alien-union (symbol-name)  (defimplementation arglist (fun)
1342    (%describe-alien symbol-name :union))    (etypecase fun
1343        (function (function-arglist fun))
1344  (defslimefun describe-alien-enum (symbol-name)      (symbol (function-arglist (or (macro-function fun)
1345    (%describe-alien symbol-name :enum))                                    (symbol-function fun))))))
1346    
1347  (defmethod arglist-string (fname)  (defun function-arglist (fun)
1348    "Return a string describing the argument list for FNAME.    (let ((arglist
1349  The result has the format \"(...)\"."           (cond ((eval:interpreted-function-p fun)
1350    (declare (type string fname))                  (eval:interpreted-function-arglist fun))
1351    (multiple-value-bind (function condition)                 ((pcl::generic-function-p fun)
1352        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))                  (pcl:generic-function-lambda-list fun))
1353      (when condition                 ((c::byte-function-or-closure-p fun)
1354        (return-from arglist-string (format nil "(-- ~A)" condition)))                  (byte-code-function-arglist fun))
1355      (let ((arglist                 ((kernel:%function-arglist (kernel:%function-self fun))
1356             (if (not (or (fboundp function)                  (handler-case (read-arglist fun)
1357                          (functionp function)))                    (error () :not-available)))
1358                 "(-- <Unknown-Function>)"                 ;; this should work both for compiled-debug-function
1359                 (let* ((fun (or (macro-function function)                 ;; and for interpreted-debug-function
1360                                 (symbol-function function)))                 (t
1361                        (df (di::function-debug-function fun))                  (handler-case (debug-function-arglist
1362                        (arglist (kernel:%function-arglist fun)))                                 (di::function-debug-function fun))
1363                   (cond ((eval:interpreted-function-p fun)                    (di:unhandled-condition () :not-available))))))
1364                          (eval:interpreted-function-arglist fun))      (check-type arglist (or list (member :not-available)))
1365                         ((pcl::generic-function-p fun)      arglist))
1366                          (pcl::gf-pretty-arglist fun))  
1367                         (arglist arglist)  (defimplementation function-name (function)
1368                         ;; this should work both for    (cond ((eval:interpreted-function-p function)
1369                         ;; compiled-debug-function and for           (eval:interpreted-function-name function))
1370                         ;; interpreted-debug-function          ((pcl::generic-function-p function)
1371                         (df (di::debug-function-lambda-list df))           (pcl::generic-function-name function))
1372                         (t "(<arglist-unavailable>)"))))))          ((c::byte-function-or-closure-p function)
1373        (if (stringp arglist)           (c::byte-function-name function))
1374            arglist          (t (kernel:%function-name (kernel:%function-self function)))))
1375            (to-string arglist)))))  
1376    ;;; A simple case: the arglist is available as a string that we can
1377    ;;; `read'.
1378    
1379    (defun read-arglist (fn)
1380      "Parse the arglist-string of the function object FN."
1381      (let ((string (kernel:%function-arglist
1382                     (kernel:%function-self fn)))
1383            (package (find-package
1384                      (c::compiled-debug-info-package
1385                       (kernel:%code-debug-info
1386                        (vm::find-code-object fn))))))
1387        (with-standard-io-syntax
1388          (let ((*package* (or package *package*)))
1389            (read-from-string string)))))
1390    
1391    ;;; A harder case: an approximate arglist is derived from available
1392    ;;; debugging information.
1393    
1394    (defun debug-function-arglist (debug-function)
1395      "Derive the argument list of DEBUG-FUNCTION from debug info."
1396      (let ((args (di::debug-function-lambda-list debug-function))
1397            (required '())
1398            (optional '())
1399            (rest '())
1400            (key '()))
1401        ;; collect the names of debug-vars
1402        (dolist (arg args)
1403          (etypecase arg
1404            (di::debug-variable
1405             (push (di::debug-variable-symbol arg) required))
1406            ((member :deleted)
1407             (push ':deleted required))
1408            (cons
1409             (ecase (car arg)
1410               (:keyword
1411                (push (second arg) key))
1412               (:optional
1413                (push (debug-variable-symbol-or-deleted (second arg)) optional))
1414               (:rest
1415                (push (debug-variable-symbol-or-deleted (second arg)) rest))))))
1416        ;; intersperse lambda keywords as needed
1417        (append (nreverse required)
1418                (if optional (cons '&optional (nreverse optional)))
1419                (if rest (cons '&rest (nreverse rest)))
1420                (if key (cons '&key (nreverse key))))))
1421    
1422    (defun debug-variable-symbol-or-deleted (var)
1423      (etypecase var
1424        (di:debug-variable
1425         (di::debug-variable-symbol var))
1426        ((member :deleted)
1427         '#:deleted)))
1428    
1429    (defun symbol-debug-function-arglist (fname)
1430      "Return FNAME's debug-function-arglist and %function-arglist.
1431    A utility for debugging DEBUG-FUNCTION-ARGLIST."
1432      (let ((fn (fdefinition fname)))
1433        (values (debug-function-arglist (di::function-debug-function fn))
1434                (kernel:%function-arglist (kernel:%function-self fn)))))
1435    
1436    ;;; Deriving arglists for byte-compiled functions:
1437    ;;;
1438    (defun byte-code-function-arglist (fn)
1439      ;; There doesn't seem to be much arglist information around for
1440      ;; byte-code functions.  Use the arg-count and return something like
1441      ;; (arg0 arg1 ...)
1442      (etypecase fn
1443        (c::simple-byte-function
1444         (loop for i from 0 below (c::simple-byte-function-num-args fn)
1445               collect (make-arg-symbol i)))
1446        (c::hairy-byte-function
1447         (hairy-byte-function-arglist fn))
1448        (c::byte-closure
1449         (byte-code-function-arglist (c::byte-closure-function fn)))))
1450    
1451    (defun make-arg-symbol (i)
1452      (make-symbol (format nil "~A~D" (string 'arg) i)))
1453    
1454    ;;; A "hairy" byte-function is one that takes a variable number of
1455    ;;; arguments. `hairy-byte-function' is a type from the bytecode
1456    ;;; interpreter.
1457    ;;;
1458    (defun hairy-byte-function-arglist (fn)
1459      (let ((counter -1))
1460        (flet ((next-arg () (make-arg-symbol (incf counter))))
1461          (with-struct (c::hairy-byte-function- min-args max-args rest-arg-p
1462                                                keywords-p keywords) fn
1463            (let ((arglist '())
1464                  (optional (- max-args min-args)))
1465              ;; XXX isn't there a better way to write this?
1466              ;; (Looks fine to me. -luke)
1467              (dotimes (i min-args)
1468                (push (next-arg) arglist))
1469              (when (plusp optional)
1470                (push '&optional arglist)
1471                (dotimes (i optional)
1472                  (push (next-arg) arglist)))
1473              (when rest-arg-p
1474                (push '&rest arglist)
1475                (push (next-arg) arglist))
1476              (when keywords-p
1477                (push '&key arglist)
1478                (loop for (key _ __) in keywords
1479                      do (push key arglist))
1480                (when (eq keywords-p :allow-others)
1481                  (push '&allow-other-keys arglist)))
1482              (nreverse arglist))))))
1483    
1484    
1485  ;;;; Miscellaneous.  ;;;; Miscellaneous.
1486    
1487  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
1488    (walker:macroexpand-all form))    (walker:macroexpand-all form))
1489    
1490  (defun tracedp (fname)  (defimplementation compiler-macroexpand-1 (form &optional env)
1491    (gethash (debug::trace-fdefinition fname)    (ext:compiler-macroexpand-1 form env))
            debug::*traced-functions*))  
   
 (defslimefun toggle-trace-fdefinition (fname-string)  
   (let ((fname (from-string fname-string)))  
     (cond ((tracedp fname)  
            (debug::untrace-1 fname)  
            (format nil "~S is now untraced." fname))  
           (t  
            (debug::trace-1 fname (debug::make-trace-info))  
            (format nil "~S is now traced." fname)))))  
1492    
1493  (defslimefun set-default-directory (directory)  (defimplementation compiler-macroexpand (form &optional env)
1494      (ext:compiler-macroexpand form env))
1495    
1496    (defimplementation set-default-directory (directory)
1497    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
1498    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
1499    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
1500    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
1501    (namestring (ext:default-directory)))    (default-directory))
   
   
 ;;;; Source-paths  
   
 ;;; 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))))))  
1502    
1503  (defun code-location-stream-position (code-location stream)  (defimplementation default-directory ()
1504    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the    (namestring (ext:default-directory)))
 toplevel-form-number and form-number from CODE-LOCATION and use that  
 to find the position of the corresponding form."  
   (let* ((location (debug::maybe-block-start-location code-location))  
          (tlf-offset (di:code-location-top-level-form-offset location))  
          (form-number (di:code-location-form-number location))  
          (*read-suppress* t))  
     (dotimes (i tlf-offset) (read stream))  
     (multiple-value-bind (tlf position-map) (read-and-record-source-map stream)  
       (let* ((path-table (di:form-number-translations tlf 0))  
              (source-path  
               (if (<= (length path-table) form-number) ; source out of sync?  
                   (list 0)              ; should probably signal a condition  
                   (reverse (cdr (aref path-table form-number))))))  
         (source-path-source-position source-path tlf position-map)))))  
   
 (defun code-location-string-offset (code-location string)  
   (with-input-from-string (s string)  
     (code-location-stream-position code-location s)))  
   
 (defun code-location-file-position (code-location filename)  
   (with-open-file (s filename :direction :input)  
     (code-location-stream-position code-location s)))  
1505    
1506  (defun debug-source-info-from-emacs-buffer-p (debug-source)  (defimplementation getpid ()
1507    (let ((info (c::debug-source-info debug-source)))    (unix:unix-getpid))
     (and info  
          (consp info)  
          (eq :emacs-buffer (car info)))))  
1508    
1509  (defun source-location-from-code-location (code-location)  (defimplementation lisp-implementation-type-name ()
1510    "Return the source location for CODE-LOCATION."    "cmucl")
   (let ((debug-fun (di:code-location-debug-function code-location)))  
     (when (di::bogus-debug-function-p debug-fun)  
       (error "Bogus debug function: ~A" debug-fun)))  
   (let* ((debug-source (di:code-location-debug-source code-location))  
          (from (di:debug-source-from debug-source))  
          (name (di:debug-source-name debug-source)))  
     (ecase from  
       (:file  
        (make-location (list :file (unix-truename name))  
                       (list :position (1+ (code-location-file-position  
                                            code-location name)))))  
       (:stream  
        (assert (debug-source-info-from-emacs-buffer-p debug-source))  
        (let ((info (c::debug-source-info debug-source)))  
          (make-location  
           (list :buffer (getf info :emacs-buffer))  
           (list :position (+ (getf info :emacs-buffer-offset)  
                              (code-location-string-offset  
                               code-location  
                               (getf info :emacs-buffer-string)))))))  
       (:lisp  
        (make-location  
         (list :source-form (with-output-to-string (*standard-output*)  
                              (debug::print-code-location-source-form  
                               code-location 100 t)))  
         (list :position 1))))))  
1511    
1512  (defun code-location-source-location (code-location)  (defimplementation quit-lisp ()
1513    "Safe wrapper around `code-location-from-source-location'."    (ext::quit))
   (safe-definition-finding  
    (source-location-from-code-location code-location)))  
1514    
1515  (defslimefun getpid ()  ;;; source-path-{stream,file,string,etc}-position moved into
1516    (unix:unix-getpid))  ;;; swank-source-path-parser
1517    
1518    
1519  ;;;; Debugging  ;;;; Debugging
1520    
1521  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
1522    
1523  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
1524    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
1525    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
          (*sldb-restarts* (compute-restarts *swank-debugger-condition*))  
1526           (debug:*stack-top-hint* nil)           (debug:*stack-top-hint* nil)
1527           (*debugger-hook* nil)           (kernel:*current-level* 0))
1528           (*readtable* (or debug:*debug-readtable* *readtable*))      (handler-bind ((di::unhandled-condition
          (*print-level* debug:*debug-print-level*)  
          (*print-length* debug:*debug-print-length*)  
          (*print-readably* nil))  
     (handler-bind ((di:debug-condition  
1529                      (lambda (condition)                      (lambda (condition)
1530                        (signal (make-condition                        (error (make-condition
1531                                 'sldb-condition                                'sldb-condition
1532                                 :original-condition condition)))))                                :original-condition condition)))))
1533        (funcall debugger-loop-fn))))        (unwind-protect
1534               (progn
1535  (defun format-restarts-for-emacs ()               #+(or)(sys:scrub-control-stack)
1536    "Return a list of restarts for *swank-debugger-condition* in a               (funcall debugger-loop-fn))
1537  format suitable for Emacs."          #+(or)(sys:scrub-control-stack)
1538    (loop for restart in *sldb-restarts*          ))))
1539          collect (list (princ-to-string (restart-name restart))  
1540                        (princ-to-string restart))))  (defun frame-down (frame)
1541      (handler-case (di:frame-down frame)
1542  (defun format-condition-for-emacs ()      (di:no-debug-info () nil)))
   (format nil "~A~%   [Condition of type ~S]"  
           (debug::safe-condition-message *swank-debugger-condition*)  
           (type-of *swank-debugger-condition*)))  
1543    
1544  (defun nth-frame (index)  (defun nth-frame (index)
1545    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (frame-down frame))
1546         (i index (1- i)))         (i index (1- i)))
1547        ((zerop i) frame)))        ((zerop i) frame)))
1548    
1549  (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."  
1550    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
1551      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (frame-down f)
1552            for i from start below end            for i from start below end
1553            while f            while f collect f)))
           collect f)))  
1554    
1555  (defmethod backtrace (start end)  (defimplementation print-frame (frame stream)
1556    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (let ((*standard-output* stream))
1557        (handler-case
1558            (debug::print-frame-call frame :verbosity 1 :number nil)
1559          (error (e)
1560            (ignore-errors (princ e stream))))))
1561    
1562    (defimplementation frame-source-location (index)
1563      (let ((frame (nth-frame index)))
1564        (cond ((foreign-frame-p frame) (foreign-frame-source-location frame))
1565              ((code-location-source-location (di:frame-code-location frame))))))
1566    
1567  (defmethod debugger-info-for-emacs (start end)  (defimplementation eval-in-frame (form index)
1568    (list (format-condition-for-emacs)    (di:eval-in-frame (nth-frame index) form))
         (format-restarts-for-emacs)  
         (backtrace start end)))  
1569    
1570  (defmethod frame-source-location-for-emacs (index)  (defun frame-debug-vars (frame)
1571    (code-location-source-location (di:frame-code-location (nth-frame index))))    "Return a vector of debug-variables in frame."
1572      (let ((loc (di:frame-code-location frame)))
1573        (remove-if
1574         (lambda (v)
1575           (not (eq (di:debug-variable-validity v loc) :valid)))
1576         (di::debug-function-debug-variables (di:frame-debug-function frame)))))
1577    
1578    (defun debug-var-value (var frame)
1579      (let* ((loc (di:frame-code-location frame))
1580             (validity (di:debug-variable-validity var loc)))
1581        (ecase validity
1582          (:valid (di:debug-variable-value var frame))
1583          ((:invalid :unknown) (make-symbol (string validity))))))
1584    
1585    (defimplementation frame-locals (index)
1586      (let ((frame (nth-frame index)))
1587        (loop for v across (frame-debug-vars frame)
1588              collect (list :name (di:debug-variable-symbol v)
1589                            :id (di:debug-variable-id v)
1590                            :value (debug-var-value v frame)))))
1591    
1592    (defimplementation frame-var-value (frame var)
1593      (let* ((frame (nth-frame frame))
1594             (dvar (aref (frame-debug-vars frame) var)))
1595        (debug-var-value dvar frame)))
1596    
1597    (defimplementation frame-catch-tags (index)
1598      (mapcar #'car (di:frame-catches (nth-frame index))))
1599    
1600    (defimplementation return-from-frame (index form)
1601      (let ((sym (find-symbol (string 'find-debug-tag-for-frame)
1602                              :debug-internals)))
1603        (if sym
1604            (let* ((frame (nth-frame index))
1605                   (probe (funcall sym frame)))
1606              (cond (probe (throw (car probe) (eval-in-frame form index)))
1607                    (t (format nil "Cannot return from frame: ~S" frame))))
1608            "return-from-frame is not implemented in this version of CMUCL.")))
1609    
1610  (defmethod eval-in-frame (form index)  (defimplementation activate-stepping (frame)
1611    (di:eval-in-frame (nth-frame index) form))    (set-step-breakpoints (nth-frame frame)))
1612    
1613  (defslimefun pprint-eval-string-in-frame (string index)  (defimplementation sldb-break-on-return (frame)
1614    (swank-pprint    (break-on-return (nth-frame frame)))
    (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)  
   (let* ((frame (nth-frame index))  
          (location (di:frame-code-location frame))  
          (debug-function (di:frame-debug-function frame))  
          (debug-variables (di::debug-function-debug-variables debug-function)))  
     (loop for v across debug-variables  
           collect (list  
                    :symbol (di:debug-variable-symbol v)  
                    :id (di:debug-variable-id v)  
                    :value-string  
                    (if (eq (di:debug-variable-validity v location)  
                            :valid)  
                        (to-string (di:debug-variable-value v frame))  
                        "<not-available>")))))  
   
 (defmethod frame-catch-tags (index)  
   (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  
         collect `(,tag . ,(code-location-source-location code-location))))  
1615    
1616  (defslimefun invoke-nth-restart (index)  ;;; We set the breakpoint in the caller which might be a bit confusing.
1617    (invoke-restart-interactively (nth-restart index)))  ;;;
1618    (defun break-on-return (frame)
1619      (let* ((caller (di:frame-down frame))
1620             (cl (di:frame-code-location caller)))
1621        (flet ((hook (frame bp)
1622                 (when (frame-pointer= frame caller)
1623                   (di:delete-breakpoint bp)
1624                   (signal-breakpoint bp frame))))
1625          (let* ((info (ecase (di:code-location-kind cl)
1626                         ((:single-value-return :unknown-return) nil)
1627                         (:known-return (debug-function-returns
1628                                         (di:frame-debug-function frame)))))
1629                 (bp (di:make-breakpoint #'hook cl :kind :code-location
1630                                         :info info)))
1631            (di:activate-breakpoint bp)
1632            `(:ok ,(format nil "Set breakpoint in ~A" caller))))))
1633    
1634    (defun frame-pointer= (frame1 frame2)
1635      "Return true if the frame pointers of FRAME1 and FRAME2 are the same."
1636      (sys:sap= (di::frame-pointer frame1) (di::frame-pointer frame2)))
1637    
1638    ;;; The PC in escaped frames at a single-return-value point is
1639    ;;; actually vm:single-value-return-byte-offset bytes after the
1640    ;;; position given in the debug info.  Here we try to recognize such
1641    ;;; cases.
1642    ;;;
1643    (defun next-code-locations (frame code-location)
1644      "Like `debug::next-code-locations' but be careful in escaped frames."
1645      (let ((next (debug::next-code-locations code-location)))
1646        (flet ((adjust-pc ()
1647                 (let ((cl (di::copy-compiled-code-location code-location)))
1648                   (incf (di::compiled-code-location-pc cl)
1649                         vm:single-value-return-byte-offset)
1650                   cl)))
1651          (cond ((and (di::compiled-frame-escaped frame)
1652                      (eq (di:code-location-kind code-location)
1653                          :single-value-return)
1654                      (= (length next) 1)
1655                      (di:code-location= (car next) (adjust-pc)))
1656                 (debug::next-code-locations (car next)))
1657                (t
1658                 next)))))
1659    
1660    (defun set-step-breakpoints (frame)
1661      (let ((cl (di:frame-code-location frame)))
1662        (when (di:debug-block-elsewhere-p (di:code-location-debug-block cl))
1663          (error "Cannot step in elsewhere code"))
1664        (let* ((debug::*bad-code-location-types*
1665                (remove :call-site debug::*bad-code-location-types*))
1666               (next (next-code-locations frame cl)))
1667          (cond (next
1668                 (let ((steppoints '()))
1669                   (flet ((hook (bp-frame bp)
1670                            (signal-breakpoint bp bp-frame)
1671                            (mapc #'di:delete-breakpoint steppoints)))
1672                     (dolist (code-location next)
1673                       (let ((bp (di:make-breakpoint #'hook code-location
1674                                                     :kind :code-location)))
1675                         (di:activate-breakpoint bp)
1676                         (push bp steppoints))))))
1677                (t
1678                 (break-on-return frame))))))
1679    
1680    
1681    ;; XXX the return values at return breakpoints should be passed to the
1682    ;; user hooks. debug-int.lisp should be changed to do this cleanly.
1683    
1684    ;;; The sigcontext and the PC for a breakpoint invocation are not
1685    ;;; passed to user hook functions, but we need them to extract return
1686    ;;; values. So we advice di::handle-breakpoint and bind the values to
1687    ;;; special variables.
1688    ;;;
1689    (defvar *breakpoint-sigcontext*)
1690    (defvar *breakpoint-pc*)
1691    
1692  (defslimefun sldb-abort ()  ;; XXX don't break old versions without fwrappers.  Remove this one day.
1693    (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))  #+#.(cl:if (cl:find-package :fwrappers) '(and) '(or))
1694    (progn
1695      (fwrappers:define-fwrapper bind-breakpoint-sigcontext (offset c sigcontext)
1696        (let ((*breakpoint-sigcontext* sigcontext)
1697              (*breakpoint-pc* offset))
1698          (fwrappers:call-next-function)))
1699      (fwrappers:set-fwrappers 'di::handle-breakpoint '())
1700      (fwrappers:fwrap 'di::handle-breakpoint #'bind-breakpoint-sigcontext))
1701    
1702    (defun sigcontext-object (sc index)
1703      "Extract the lisp object in sigcontext SC at offset INDEX."
1704      (kernel:make-lisp-obj (vm:sigcontext-register sc index)))
1705    
1706    (defun known-return-point-values (sigcontext sc-offsets)
1707      (let ((fp (system:int-sap (vm:sigcontext-register sigcontext
1708                                                        vm::cfp-offset))))
1709        (system:without-gcing
1710         (loop for sc-offset across sc-offsets
1711               collect (di::sub-access-debug-var-slot fp sc-offset sigcontext)))))
1712    
1713    ;;; CMUCL returns the first few values in registers and the rest on
1714    ;;; the stack. In the multiple value case, the number of values is
1715    ;;; stored in a dedicated register. The values of the registers can be
1716    ;;; accessed in the sigcontext for the breakpoint.  There are 3 kinds
1717    ;;; of return conventions: :single-value-return, :unknown-return, and
1718    ;;; :known-return.
1719    ;;;
1720    ;;; The :single-value-return convention returns the value in a
1721    ;;; register without setting the nargs registers.
1722    ;;;
1723    ;;; The :unknown-return variant is used for multiple values. A
1724    ;;; :unknown-return point consists actually of 2 breakpoints: one for
1725    ;;; the single value case and one for the general case.  The single
1726    ;;; value breakpoint comes vm:single-value-return-byte-offset after
1727    ;;; the multiple value breakpoint.
1728    ;;;
1729    ;;; The :known-return convention is used by local functions.
1730    ;;; :known-return is currently not supported because we don't know
1731    ;;; where the values are passed.
1732    ;;;
1733    (defun breakpoint-values (breakpoint)
1734      "Return the list of return values for a return point."
1735      (flet ((1st (sc) (sigcontext-object sc (car vm::register-arg-offsets))))
1736        (let ((sc (locally (declare (optimize (speed 0)))
1737                    (alien:sap-alien *breakpoint-sigcontext* (* unix:sigcontext))))
1738              (cl (di:breakpoint-what breakpoint)))
1739          (ecase (di:code-location-kind cl)
1740            (:single-value-return
1741             (list (1st sc)))
1742            (:known-return
1743             (let ((info (di:breakpoint-info breakpoint)))
1744               (if (vectorp info)
1745                   (known-return-point-values sc info)
1746                   (progn
1747                     ;;(break)
1748                     (list "<<known-return convention not supported>>" info)))))
1749            (:unknown-return
1750             (let ((mv-return-pc (di::compiled-code-location-pc cl)))
1751               (if (= mv-return-pc *breakpoint-pc*)
1752                   (mv-function-end-breakpoint-values sc)
1753                   (list (1st sc)))))))))
1754    
1755    ;; XXX: di::get-function-end-breakpoint-values takes 2 arguments in
1756    ;; newer versions of CMUCL (after ~March 2005).
1757    (defun mv-function-end-breakpoint-values (sigcontext)
1758      (let ((sym (find-symbol "FUNCTION-END-BREAKPOINT-VALUES/STANDARD" :di)))
1759        (cond (sym (funcall sym sigcontext))
1760              (t (funcall 'di::get-function-end-breakpoint-values sigcontext)))))
1761    
1762    (defun debug-function-returns (debug-fun)
1763      "Return the return style of DEBUG-FUN."
1764      (let* ((cdfun (di::compiled-debug-function-compiler-debug-fun debug-fun)))
1765        (c::compiled-debug-function-returns cdfun)))
1766    
1767    (define-condition breakpoint (simple-condition)
1768      ((message :initarg :message :reader breakpoint.message)
1769       (values  :initarg :values  :reader breakpoint.values))
1770      (:report (lambda (c stream) (princ (breakpoint.message c) stream))))
1771    
1772    (defimplementation condition-extras (condition)
1773      (typecase condition
1774        (breakpoint
1775         ;; pop up the source buffer
1776         `((:show-frame-source 0)))
1777        (t '())))
1778    
1779    (defun signal-breakpoint (breakpoint frame)
1780      "Signal a breakpoint condition for BREAKPOINT in FRAME.
1781    Try to create a informative message."
1782      (flet ((brk (values fstring &rest args)
1783               (let ((msg (apply #'format nil fstring args))
1784                     (debug:*stack-top-hint* frame))
1785                 (break 'breakpoint :message msg :values values))))
1786        (with-struct (di::breakpoint- kind what) breakpoint
1787          (case kind
1788            (:code-location
1789             (case (di:code-location-kind what)
1790               ((:single-value-return :known-return :unknown-return)
1791                (let ((values (breakpoint-values breakpoint)))
1792                  (brk values "Return value: ~{~S ~}" values)))
1793               (t
1794                #+(or)
1795                (when (eq (di:code-location-kind what) :call-site)
1796                  (call-site-function breakpoint frame))
1797                (brk nil "Breakpoint: ~S ~S"
1798                     (di:code-location-kind what)
1799                     (di::compiled-code-location-pc what)))))
1800            (:function-start
1801             (brk nil "Function start breakpoint"))
1802            (t (brk nil "Breakpoint: ~A in ~A" breakpoint frame))))))
1803    
1804    (defimplementation sldb-break-at-start (fname)
1805      (let ((debug-fun (di:function-debug-function (coerce fname 'function))))
1806        (cond ((not debug-fun)
1807               `(:error ,(format nil "~S has no debug-function" fname)))
1808              (t
1809               (flet ((hook (frame bp &optional args cookie)
1810                        (declare (ignore args cookie))
1811                        (signal-breakpoint bp frame)))
1812                 (let ((bp (di:make-breakpoint #'hook debug-fun
1813                                               :kind :function-start)))
1814                   (di:activate-breakpoint bp)
1815                   `(:ok ,(format nil "Set breakpoint in ~S" fname))))))))
1816    
1817    (defun frame-cfp (frame)
1818      "Return the Control-Stack-Frame-Pointer for FRAME."
1819      (etypecase frame
1820        (di::compiled-frame (di::frame-pointer frame))
1821        ((or di::interpreted-frame null) -1)))
1822    
1823    (defun frame-ip (frame)
1824      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1825      (if (not frame)
1826          -1
1827          (let ((debug-fun (di::frame-debug-function frame)))
1828            (etypecase debug-fun
1829              (di::compiled-debug-function
1830               (let* ((code-loc (di:frame-code-location frame))
1831                      (component (di::compiled-debug-function-component debug-fun))
1832                      (pc (di::compiled-code-location-pc code-loc))
1833                      (ip (sys:without-gcing
1834                           (sys:sap-int
1835                            (sys:sap+ (kernel:code-instructions component) pc)))))
1836                 (values ip pc)))
1837              (di::interpreted-debug-function -1)
1838              (di::bogus-debug-function
1839               #-x86 -1
1840               #+x86
1841               (let ((fp (di::frame-pointer (di:frame-up frame))))
1842                 (multiple-value-bind (ra ofp) (di::x86-call-context fp)
1843                   (declare (ignore ofp))
1844                   (values ra 0))))))))
1845    
1846    (defun frame-registers (frame)
1847      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1848      (let* ((cfp (frame-cfp frame))
1849             (csp (frame-cfp (di::frame-up frame)))
1850             (ip (frame-ip frame))
1851             (ocfp (frame-cfp (di::frame-down frame)))
1852             (lra (frame-ip (di::frame-down frame))))
1853        (values csp cfp ip ocfp lra)))
1854    
1855    (defun print-frame-registers (frame-number)
1856      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1857        (flet ((fixnum (p) (etypecase p
1858                             (integer p)
1859                             (sys:system-area-pointer (sys:sap-int p)))))
1860          (apply #'format t "~
1861    ~8X  Stack Pointer
1862    ~8X  Frame Pointer
1863    ~8X  Instruction Pointer
1864    ~8X  Saved Frame Pointer
1865    ~8X  Saved Instruction Pointer~%" (mapcar #'fixnum
1866                          (multiple-value-list (frame-registers frame)))))))
1867    
1868    (defvar *gdb-program-name* "/usr/bin/gdb")
1869    
1870    (defimplementation disassemble-frame (frame-number)
1871      (print-frame-registers frame-number)
1872      (terpri)
1873      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1874             (debug-fun (di::frame-debug-function frame)))
1875        (etypecase debug-fun
1876          (di::compiled-debug-function
1877           (let* ((component (di::compiled-debug-function-component debug-fun))
1878                  (fun (di:debug-function-function debug-fun)))
1879             (if fun
1880                 (disassemble fun)
1881                 (disassem:disassemble-code-component component))))
1882          (di::bogus-debug-function
1883           (cond ((probe-file *gdb-program-name*)
1884                  (let ((ip (sys:sap-int (frame-ip frame))))
1885                    (princ (gdb-command "disas 0x~x" ip))))
1886                 (t
1887                  (format t "~%[Disassembling bogus frames not implemented]")))))))
1888    
1889    (defmacro with-temporary-file ((stream filename) &body body)
1890      `(call/temporary-file (lambda (,stream ,filename) . ,body)))
1891    
1892    (defun call/temporary-file (fun)
1893      (let ((name (system::pick-temporary-file-name)))
1894        (unwind-protect
1895             (with-open-file (stream name :direction :output :if-exists :supersede)
1896               (funcall fun stream name))
1897          (delete-file name))))
1898    
1899    (defun gdb-command (format-string &rest args)
1900      (let ((str (gdb-exec (format nil "attach ~d~%~a~%detach"
1901                                   (getpid)
1902                                   (apply #'format nil format-string args)))))
1903        (subseq str (1+ (position #\newline str)))))
1904    
1905    (defun gdb-exec (cmd)
1906      (with-temporary-file (file filename)
1907        (write-string cmd file)
1908        (force-output file)
1909        (let* ((output (make-string-output-stream))
1910               (proc (ext:run-program "gdb" `("-batch" "-x" ,filename)
1911                                      :wait t
1912                                      :output output)))
1913          (assert (eq (ext:process-status proc) :exited))
1914          (assert (eq (ext:process-exit-code proc) 0))
1915          (get-output-stream-string output))))
1916    
1917    (defun foreign-frame-p (frame)
1918      #-x86 nil
1919      #+x86 (let ((ip (frame-ip frame)))
1920              (and (sys:system-area-pointer-p ip)
1921                   (multiple-value-bind (pc code)
1922                       (di::compute-lra-data-from-pc ip)
1923                     (declare (ignore pc))
1924                     (not code)))))
1925    
1926    (defun foreign-frame-source-location (frame)
1927      (let ((ip (sys:sap-int (frame-ip frame))))
1928        (cond ((probe-file *gdb-program-name*)
1929               (parse-gdb-line-info (gdb-command "info line *0x~x" ip)))
1930              (t `(:error "no srcloc available for ~a" frame)))))
1931    
1932    ;; The output of gdb looks like:
1933    ;; Line 215 of "../../src/lisp/x86-assem.S"
1934    ;;    starts at address 0x805318c <Ldone+11>
1935    ;;    and ends at 0x805318e <Ldone+13>.
1936    ;; The ../../ are fixed up with the "target:" search list which might
1937    ;; be wrong sometimes.
1938    (defun parse-gdb-line-info (string)
1939      (with-input-from-string (*standard-input* string)
1940        (let ((w1 (read-word)))
1941          (cond ((equal w1 "Line")
1942                 (let ((line (read-word)))
1943                   (assert (equal (read-word) "of"))
1944                   (let ((file (read-word)))
1945                     (make-location (list :file
1946                                          (unix-truename
1947                                           (merge-pathnames
1948                                            (read-from-string file)
1949                                            (format nil "~a/lisp/"
1950                                                    (unix-truename "target:")))))
1951                                    (list :line (parse-integer line))))))
1952                (t `(:error ,string))))))
1953    
1954    (defun read-word (&optional (stream *standard-input*))
1955      (peek-char t stream)
1956      (concatenate 'string (loop until (whitespacep (peek-char nil stream))
1957                                 collect (read-char stream))))
1958    
1959    (defun whitespacep (char)
1960      (member char '(#\space #\newline)))
1961    
1962    
1963  ;;;; Inspecting  ;;;; Inspecting
1964    
 (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))))))  
1965  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1966    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1967      vm:function-pointer-type      vm:function-pointer-type
# Line 1152  stack." Line 1970  stack."
1970      vm:odd-fixnum-type      vm:odd-fixnum-type
1971      vm:instance-pointer-type      vm:instance-pointer-type
1972      vm:other-immediate-1-type      vm:other-immediate-1-type
1973      vm:other-pointer-type))      vm:other-pointer-type)
1974      "Names of the constants that specify type tags.
1975    The `symbol-value' of each element is a type tag.")
1976    
1977  (defconstant +header-type-symbols+  (defconstant +header-type-symbols+
1978    ;; Is there a convinient place for all those constants?    (labels ((suffixp (suffix string)
1979    (flet ((tail-comp (string tail)               (and (>= (length string) (length suffix))
1980             (and (>= (length string) (length tail))                    (string= string suffix :start1 (- (length string)
1981                  (string= string tail :start1 (- (length string)                                                      (length suffix)))))
1982                                                  (length tail))))))             (header-type-symbol-p (x)
1983      (remove-if-not               (and (suffixp "-TYPE" (symbol-name x))
1984       (lambda (x) (and (tail-comp (symbol-name x) "-TYPE")                    (not (member x +lowtag-symbols+))
1985                        (not (member x +lowtag-symbols+))                    (boundp x)
1986                        (boundp x)                    (typep (symbol-value x) 'fixnum))))
1987                        (typep (symbol-value x) 'fixnum)))      (remove-if-not #'header-type-symbol-p
1988       (append (apropos-list "-TYPE" "VM" t)                     (append (apropos-list "-TYPE" "VM")
1989               (apropos-list "-TYPE" "BIGNUM" t)))))                             (apropos-list "-TYPE" "BIGNUM"))))
1990      "A list of names of the type codes in boxed objects.")
1991    
1992  (defun describe-primitive-type (object)  (defimplementation describe-primitive-type (object)
1993    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1994      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1995             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1996        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1997        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1998                                    vm:function-pointer-type                                   vm:function-pointer-type
1999                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
2000                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
2001                                    ))                                   ))
2002               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
2003                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
2004                                         :key #'symbol-value)))                                    :key #'symbol-value)))
2005                 (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."))  
2006    
2007  (defmethod inspected-parts (o)  (defmethod emacs-inspect ((o t))
2008    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
2009           (inspected-parts-of-value-cell o))           `("Value: " (:value ,(c:value-cell-ref o))))
2010            ((alien::alien-value-p o)
2011             (inspect-alien-value o))
2012          (t          (t
2013           (destructuring-bind (text labeledp . parts)           (cmucl-inspect o))))
              (inspect::describe-parts o)  
            (let ((parts (if labeledp  
                             (loop for (label . value) in parts  
                                   collect (cons (string label) value))  
                             (loop for value in parts  
                                   for i from 0  
                                   collect (cons (format nil "~D" i) value)))))  
              (values text parts))))))  
   
 (defun inspected-parts-of-value-cell (o)  
   (values (format nil "~A~% is a value cell." o)  
           (list (cons "Value" (c:value-cell-ref o)))))  
   
 ;; borrowed from sbcl  
 (defmethod inspected-parts ((object cons))  
   (if (consp (cdr object))  
       (inspected-parts-of-nontrivial-list object)  
       (inspected-parts-of-simple-cons object)))  
   
 (defun inspected-parts-of-simple-cons (object)  
   (values "The object is a CONS."  
           (list (cons (string 'car) (car object))  
                 (cons (string 'cdr) (cdr object)))))  
   
 (defun inspected-parts-of-nontrivial-list (object)  
   (let ((length 0)  
         (in-list object)  
         (reversed-elements nil))  
     (flet ((done (description-format)  
              (return-from inspected-parts-of-nontrivial-list  
                (values (format nil description-format length)  
                        (nreverse reversed-elements)))))  
       (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.~%")))))))  
2014    
2015  (defmethod inspected-parts ((o function))  (defun cmucl-inspect (o)
2016      (destructuring-bind (text labeledp . parts) (inspect::describe-parts o)
2017        (list* (format nil "~A~%" text)
2018               (if labeledp
2019                   (loop for (label . value) in parts
2020                         append (label-value-line label value))
2021                   (loop for value in parts  for i from 0
2022                         append (label-value-line i value))))))
2023    
2024    (defmethod emacs-inspect ((o function))
2025    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
2026      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
2027             (values             (append (label-value-line*
2028              (format nil "~A~% is a function." o)                      ("Self" (kernel:%function-self o))
2029              (list (cons "Self" (kernel:%function-self o))                      ("Next" (kernel:%function-next o))
2030                    (cons "Next" (kernel:%function-next o))                      ("Name" (kernel:%function-name o))
2031                    (cons "Name" (kernel:%function-name o))                      ("Arglist" (kernel:%function-arglist o))
2032                    (cons "Arglist" (kernel:%function-arglist o))                      ("Type" (kernel:%function-type o))
2033                    (cons "Type" (kernel:%function-type o))                      ("Code" (kernel:function-code-header o)))
2034                    (cons "Code Object" (kernel:function-code-header o)))))                     (list
2035            ((= header vm:closure-header-type)                      (with-output-to-string (s)
2036             (values (format nil "~A~% is a closure." o)                        (disassem:disassemble-function o :stream s)))))
2037                     (list*            ((= header vm:closure-header-type)
2038                      (cons "Function" (kernel:%closure-function o))             (list* (format nil "~A is a closure.~%" o)
2039                      (loop for i from 0 below (- (kernel:get-closure-length o)                    (append
2040                                                  (1- vm:closure-info-offset))                     (label-value-line "Function" (kernel:%closure-function o))
2041                            collect (cons (format nil "~D" i)                     `("Environment:" (:newline))
2042                                          (kernel:%closure-index-ref o i))))))                     (loop for i from 0 below (1- (kernel:get-closure-length o))
2043            (t (call-next-method o)))))                           append (label-value-line
2044                                     i (kernel:%closure-index-ref o i))))))
2045  (defmethod inspected-parts ((o kernel:code-component))            ((eval::interpreted-function-p o)
2046    (values (format nil "~A~% is a code data-block." o)             (cmucl-inspect o))
2047            `(("First entry point" . ,(kernel:%code-entry-points o))            (t
2048              ,@(loop for i from vm:code-constants-offset             (call-next-method)))))
2049                      below (kernel:get-header-data o)  
2050                      collect (cons (format nil "Constant#~D" i)  (defmethod emacs-inspect ((o kernel:funcallable-instance))
2051                                    (kernel:code-header-ref o i)))    (append (label-value-line*
2052              ("Debug info" . ,(kernel:%code-debug-info o))             (:function (kernel:%funcallable-instance-function o))
2053              ("Instructions"  . ,(kernel:code-instructions o)))))             (:lexenv  (kernel:%funcallable-instance-lexenv o))
2054               (:layout  (kernel:%funcallable-instance-layout o)))
2055  (defmethod inspected-parts ((o kernel:fdefn))            (cmucl-inspect o)))
2056    (values (format nil "~A~% is a fdefn object." o)  
2057            `(("Name" . ,(kernel:fdefn-name o))  (defmethod emacs-inspect ((o kernel:code-component))
2058              ("Function" . ,(kernel:fdefn-function o)))))    (append
2059       (label-value-line*
2060  ;;; Local Variables:      ("code-size" (kernel:%code-code-size o))
2061  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))      ("entry-points" (kernel:%code-entry-points o))
2062  ;;; End:      ("debug-info" (kernel:%code-debug-info o))
2063        ("trace-table-offset" (kernel:code-header-ref
2064                               o vm:code-trace-table-offset-slot)))
2065       `("Constants:" (:newline))
2066       (loop for i from vm:code-constants-offset
2067             below (kernel:get-header-data o)
2068             append (label-value-line i (kernel:code-header-ref o i)))
2069       `("Code:"
2070         (:newline)
2071         , (with-output-to-string (*standard-output*)
2072             (cond ((c::compiled-debug-info-p (kernel:%code-debug-info o))
2073                    (disassem:disassemble-code-component o))
2074                   ((or
2075                     (c::debug-info-p (kernel:%code-debug-info o))
2076                     (consp (kernel:code-header-ref
2077                             o vm:code-trace-table-offset-slot)))
2078                    (c:disassem-byte-component o))
2079                   (t
2080                    (disassem:disassemble-memory
2081                     (disassem::align
2082                      (+ (logandc2 (kernel:get-lisp-obj-address o)
2083                                   vm:lowtag-mask)
2084                         (* vm:code-constants-offset vm:word-bytes))
2085                      (ash 1 vm:lowtag-bits))
2086                     (ash (kernel:%code-code-size o) vm:word-shift))))))))
2087    
2088    (defmethod emacs-inspect ((o kernel:fdefn))
2089      (label-value-line*
2090       ("name" (kernel:fdefn-name o))
2091       ("function" (kernel:fdefn-function o))
2092       ("raw-addr" (sys:sap-ref-32
2093                    (sys:int-sap (kernel:get-lisp-obj-address o))
2094                    (* vm:fdefn-raw-addr-slot vm:word-bytes)))))
2095    
2096    #+(or)
2097    (defmethod emacs-inspect ((o array))
2098      (if (typep o 'simple-array)
2099          (call-next-method)
2100          (label-value-line*
2101           (:header (describe-primitive-type o))
2102           (:rank (array-rank o))
2103           (:fill-pointer (kernel:%array-fill-pointer o))
2104           (:fill-pointer-p (kernel:%array-fill-pointer-p o))
2105           (:elements (kernel:%array-available-elements o))
2106           (:data (kernel:%array-data-vector o))
2107           (:displacement (kernel:%array-displacement o))
2108           (:displaced-p (kernel:%array-displaced-p o))
2109           (:dimensions (array-dimensions o)))))
2110    
2111    (defmethod emacs-inspect ((o simple-vector))
2112      (append
2113       (label-value-line*
2114        (:header (describe-primitive-type o))
2115        (:length (c::vector-length o)))
2116       (loop for i below (length o)
2117             append (label-value-line i (aref o i)))))
2118    
2119    (defun inspect-alien-record (alien)
2120      (with-struct (alien::alien-value- sap type) alien
2121        (with-struct (alien::alien-record-type- kind name fields) type
2122          (append
2123           (label-value-line*
2124            (:sap sap)
2125            (:kind kind)
2126            (:name name))
2127           (loop for field in fields
2128                 append (let ((slot (alien::alien-record-field-name field)))
2129                          (declare (optimize (speed 0)))
2130                          (label-value-line slot (alien:slot alien slot))))))))
2131    
2132    (defun inspect-alien-pointer (alien)
2133      (with-struct (alien::alien-value- sap type) alien
2134        (label-value-line*
2135         (:sap sap)
2136         (:type type)
2137         (:to (alien::deref alien)))))
2138    
2139    (defun inspect-alien-value (alien)
2140      (typecase (alien::alien-value-type alien)
2141        (alien::alien-record-type (inspect-alien-record alien))
2142        (alien::alien-pointer-type (inspect-alien-pointer alien))
2143        (t (cmucl-inspect alien))))
2144    
2145    ;;;; Profiling
2146    (defimplementation profile (fname)
2147      (eval `(profile:profile ,fname)))
2148    
2149    (defimplementation unprofile (fname)
2150      (eval `(profile:unprofile ,fname)))
2151    
2152    (defimplementation unprofile-all ()
2153      (eval `(profile:unprofile))
2154      "All functions unprofiled.")
2155    
2156    (defimplementation profile-report ()
2157      (eval `(profile:report-time)))
2158    
2159    (defimplementation profile-reset ()
2160      (eval `(profile:reset-time))
2161      "Reset profiling counters.")
2162    
2163    (defimplementation profiled-functions ()
2164      profile:*timed-functions*)
2165    
2166    (defimplementation profile-package (package callers methods)
2167      (profile:profile-all :package package
2168                           :callers-p callers
2169                           #-cmu18e :methods #-cmu18e methods))
2170    
2171    
2172    ;;;; Multiprocessing
2173    
2174    #+mp
2175    (progn
2176      (defimplementation initialize-multiprocessing (continuation)
2177        (mp::init-multi-processing)
2178        (mp:make-process continuation :name "swank")
2179        ;; Threads magic: this never returns! But top-level becomes
2180        ;; available again.
2181        (unless mp::*idle-process*
2182          (mp::startup-idle-and-top-level-loops)))
2183    
2184      (defimplementation spawn (fn &key name)
2185        (mp:make-process fn :name (or name "Anonymous")))
2186    
2187      (defvar *thread-id-counter* 0)
2188    
2189      (defimplementation thread-id (thread)
2190        (or (getf (mp:process-property-list thread) 'id)
2191            (setf (getf (mp:process-property-list thread) 'id)
2192                  (incf *thread-id-counter*))))
2193    
2194      (defimplementation find-thread (id)
2195        (find id (all-threads)
2196              :key (lambda (p) (getf (mp:process-property-list p) 'id))))
2197    
2198      (defimplementation thread-name (thread)
2199        (mp:process-name thread))
2200    
2201      (defimplementation thread-status (thread)
2202        (mp:process-whostate thread))
2203    
2204      (defimplementation current-thread ()
2205        mp:*current-process*)
2206    
2207      (defimplementation all-threads ()
2208        (copy-list mp:*all-processes*))
2209    
2210      (defimplementation interrupt-thread (thread fn)
2211        (mp:process-interrupt thread fn))
2212    
2213      (defimplementation kill-thread (thread)
2214        (mp:destroy-process thread))
2215    
2216      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
2217    
2218      (defstruct (mailbox (:conc-name mailbox.))
2219        (mutex (mp:make-lock "process mailbox"))
2220        (queue '() :type list))
2221    
2222      (defun mailbox (thread)
2223        "Return THREAD's mailbox."
2224        (mp:with-lock-held (*mailbox-lock*)
2225          (or (getf (mp:process-property-list thread) 'mailbox)
2226              (setf (getf (mp:process-property-list thread) 'mailbox)
2227                    (make-mailbox)))))
2228    
2229      (defimplementation send (thread message)
2230        (check-slime-interrupts)
2231        (let* ((mbox (mailbox thread)))
2232          (mp:with-lock-held ((mailbox.mutex mbox))
2233            (setf (mailbox.queue mbox)
2234                  (nconc (mailbox.queue mbox) (list message))))))
2235    
2236      (defimplementation receive-if (test &optional timeout)
2237        (let ((mbox (mailbox mp:*current-process*)))
2238          (assert (or (not timeout) (eq timeout t)))
2239          (loop
2240           (check-slime-interrupts)
2241           (mp:with-lock-held ((mailbox.mutex mbox))
2242             (let* ((q (mailbox.queue mbox))
2243                    (tail (member-if test q)))
2244               (when tail
2245                 (setf (mailbox.queue mbox)
2246                       (nconc (ldiff q tail) (cdr tail)))
2247                 (return (car tail)))))
2248           (when (eq timeout t) (return (values nil t)))
2249           (mp:process-wait-with-timeout
2250            "receive-if" 0.5
2251            (lambda () (some test (mailbox.queue mbox)))))))
2252    
2253    
2254      ) ;; #+mp
2255    
2256    
2257    
2258    ;;;; GC hooks
2259    ;;;
2260    ;;; Display GC messages in the echo area to avoid cluttering the
2261    ;;; normal output.
2262    ;;;
2263    
2264    ;; this should probably not be here, but where else?
2265    (defun background-message (message)
2266      (funcall (find-symbol (string :background-message) :swank)
2267               message))
2268    
2269    (defun print-bytes (nbytes &optional stream)
2270      "Print the number NBYTES to STREAM in KB, MB, or GB units."
2271      (let ((names '((0 bytes) (10 kb) (20 mb) (30 gb) (40 tb) (50 eb))))
2272        (multiple-value-bind (power name)
2273            (loop for ((p1 n1) (p2 n2)) on names
2274                  while n2 do
2275                  (when (<= (expt 2 p1) nbytes (1- (expt 2 p2)))
2276                    (return (values p1 n1))))
2277          (cond (name
2278                 (format stream "~,1F ~A" (/ nbytes (expt 2 power)) name))
2279                (t
2280                 (format stream "~:D bytes" nbytes))))))
2281    
2282    (defconstant gc-generations 6)
2283    
2284    #+gencgc
2285    (defun generation-stats ()
2286      "Return a string describing the size distribution among the generations."
2287      (let* ((alloc (loop for i below gc-generations
2288                          collect (lisp::gencgc-stats i)))
2289             (sum (coerce (reduce #'+ alloc) 'float)))
2290        (format nil "~{~3F~^/~}"
2291                (mapcar (lambda (size) (/ size sum))
2292                        alloc))))
2293    
2294    (defvar *gc-start-time* 0)
2295    
2296    (defun pre-gc-hook (bytes-in-use)
2297      (setq *gc-start-time* (get-internal-real-time))
2298      (let ((msg (format nil "[Commencing GC with ~A in use.]"
2299                         (print-bytes bytes-in-use))))
2300        (background-message msg)))
2301    
2302    (defun post-gc-hook (bytes-retained bytes-freed trigger)
2303      (declare (ignore trigger))
2304      (let* ((seconds (/ (- (get-internal-real-time) *gc-start-time*)
2305                         internal-time-units-per-second))
2306             (msg (format nil "[GC done. ~A freed  ~A retained  ~A  ~4F sec]"
2307                         (print-bytes bytes-freed)
2308                         (print-bytes bytes-retained)
2309                         #+gencgc(generation-stats)
2310                         #-gencgc""
2311                         seconds)))
2312        (background-message msg)))
2313    
2314    (defun install-gc-hooks ()
2315      (setq ext:*gc-notify-before* #'pre-gc-hook)
2316      (setq ext:*gc-notify-after* #'post-gc-hook))
2317    
2318    (defun remove-gc-hooks ()
2319      (setq ext:*gc-notify-before* #'lisp::default-gc-notify-before)
2320      (setq ext:*gc-notify-after* #'lisp::default-gc-notify-after))
2321    
2322    (defvar *install-gc-hooks* t
2323      "If non-nil install GC hooks")
2324    
2325    (defimplementation emacs-connected ()
2326      (when *install-gc-hooks*
2327        (install-gc-hooks)))
2328    
2329    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2330    ;;Trace implementations
2331    ;;In CMUCL, we have:
2332    ;; (trace <name>)
2333    ;; (trace (method <name> <qualifier>? (<specializer>+)))
2334    ;; (trace :methods t '<name>) ;;to trace all methods of the gf <name>
2335    ;; <name> can be a normal name or a (setf name)
2336    
2337    (defun tracedp (spec)
2338      (member spec (eval '(trace)) :test #'equal))
2339    
2340    (defun toggle-trace-aux (spec &rest options)
2341      (cond ((tracedp spec)
2342             (eval `(untrace ,spec))
2343             (format nil "~S is now untraced." spec))
2344            (t
2345             (eval `(trace ,spec ,@options))
2346             (format nil "~S is now traced." spec))))
2347    
2348    (defimplementation toggle-trace (spec)
2349      (ecase (car spec)
2350        ((setf)
2351         (toggle-trace-aux spec))
2352        ((:defgeneric)
2353         (let ((name (second spec)))
2354           (toggle-trace-aux name :methods name)))
2355        ((:defmethod)
2356         (cond ((fboundp `(method ,@(cdr spec)))
2357                (toggle-trace-aux `(method ,(cdr spec))))
2358               ;; Man, is this ugly
2359               ((fboundp `(pcl::fast-method ,@(cdr spec)))
2360                (toggle-trace-aux `(pcl::fast-method ,@(cdr spec))))
2361               (t
2362                (error 'undefined-function :name (cdr spec)))))
2363        ((:call)
2364         (destructuring-bind (caller callee) (cdr spec)
2365           (toggle-trace-aux (process-fspec callee)
2366                             :wherein (list (process-fspec caller)))))
2367        ;; doesn't work properly
2368        ;; ((:labels :flet) (toggle-trace-aux (process-fspec spec)))
2369        ))
2370    
2371    (defun process-fspec (fspec)
2372      (cond ((consp fspec)
2373             (ecase (first fspec)
2374               ((:defun :defgeneric) (second fspec))
2375               ((:defmethod)
2376                `(method ,(second fspec) ,@(third fspec) ,(fourth fspec)))
2377               ((:labels) `(labels ,(third fspec) ,(process-fspec (second fspec))))
2378               ((:flet) `(flet ,(third fspec) ,(process-fspec (second fspec))))))
2379            (t
2380             fspec)))
2381    
2382    ;;; Weak datastructures
2383    
2384    (defimplementation make-weak-key-hash-table (&rest args)
2385      (apply #'make-hash-table :weak-p t args))
2386    
2387    
2388    ;;; Save image
2389    
2390    (defimplementation save-image (filename &optional restart-function)
2391      (multiple-value-bind (pid error) (unix:unix-fork)
2392        (when (not pid) (error "fork: ~A" (unix:get-unix-error-msg error)))
2393        (cond ((= pid 0)
2394               (apply #'ext:save-lisp
2395                      filename
2396                      (if restart-function
2397                          `(:init-function ,restart-function))))
2398              (t
2399               (let ((status (waitpid pid)))
2400                 (destructuring-bind (&key exited? status &allow-other-keys) status
2401                   (assert (and exited? (equal status 0)) ()
2402                           "Invalid exit status: ~a" status)))))))
2403    
2404    (defun waitpid (pid)
2405      (alien:with-alien ((status c-call:int))
2406        (let ((code (alien:alien-funcall
2407                     (alien:extern-alien
2408                      waitpid (alien:function c-call:int c-call:int
2409                                              (* c-call:int) c-call:int))
2410                     pid (alien:addr status) 0)))
2411          (cond ((= code -1) (error "waitpid: ~A" (unix:get-unix-error-msg)))
2412                (t (assert (= code pid))
2413                   (decode-wait-status status))))))
2414    
2415    (defun decode-wait-status (status)
2416      (let ((output (with-output-to-string (s)
2417                      (call-program (list (process-status-program)
2418                                          (format nil "~d" status))
2419                                    :output s))))
2420        (read-from-string output)))
2421    
2422    (defun call-program (args &key output)
2423      (destructuring-bind (program &rest args) args
2424        (let ((process (ext:run-program program args :output output)))
2425          (when (not program) (error "fork failed"))
2426          (unless (and (eq (ext:process-status process) :exited)
2427                       (= (ext:process-exit-code process) 0))
2428            (error "Non-zero exit status")))))
2429    
2430    (defvar *process-status-program* nil)
2431    
2432    (defun process-status-program ()
2433      (or *process-status-program*
2434          (setq *process-status-program*
2435                (compile-process-status-program))))
2436    
2437    (defun compile-process-status-program ()
2438      (let ((infile (system::pick-temporary-file-name
2439                     "/tmp/process-status~d~c.c")))
2440        (with-open-file (stream infile :direction :output :if-exists :supersede)
2441          (format stream "
2442    #include <stdio.h>
2443    #include <stdlib.h>
2444    #include <sys/types.h>
2445    #include <sys/wait.h>
2446    #include <assert.h>
2447    
2448    #define FLAG(value) (value ? \"t\" : \"nil\")
2449    
2450    int main (int argc, char** argv) {
2451      assert (argc == 2);
2452      {
2453        char* endptr = NULL;
2454        char* arg = argv[1];
2455        long int status = strtol (arg, &endptr, 10);
2456        assert (endptr != arg && *endptr == '\\0');
2457        printf (\"(:exited? %s :status %d :signal? %s :signal %d :coredump? %s\"
2458                \" :stopped? %s :stopsig %d)\\n\",
2459                FLAG(WIFEXITED(status)), WEXITSTATUS(status),
2460                FLAG(WIFSIGNALED(status)), WTERMSIG(status),
2461                FLAG(WCOREDUMP(status)),
2462                FLAG(WIFSTOPPED(status)), WSTOPSIG(status));
2463        fflush (NULL);
2464        return 0;
2465      }
2466    }
2467    ")
2468          (finish-output stream))
2469        (let* ((outfile (system::pick-temporary-file-name))
2470               (args (list "cc" "-o" outfile infile)))
2471          (warn "Running cc: ~{~a ~}~%" args)
2472          (call-program args :output t)
2473          (delete-file infile)
2474          outfile)))
2475    
2476    ;; (save-image "/tmp/x.core")
2477    
2478    ;; Local Variables:
2479    ;; pbook-heading-regexp:    "^;;;\\(;+\\)"
2480    ;; pbook-commentary-regexp: "^;;;\\($\\|[^;]\\)"
2481    ;; End:

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

  ViewVC Help
Powered by ViewVC 1.1.5