/[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.217 by heller, Tue Jan 5 09:00:22 2010 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    (let ((constructor (or (kernel:dd-default-constructor dd)    "Return the location of a `defstruct'."
1014                           (car (kernel::dd-constructors dd)))))    ;; Find the location in a constructor.
1015      (when (or (not constructor) (and (consp constructor)    (function-location (struct-constructor dd)))
1016                                       (not (car constructor))))  
1017        (error "Cannot locate struct without constructor: ~S"  (defun struct-constructor (dd)
1018               (kernel::dd-name dd)))    "Return a constructor function from a defstruct definition.
1019      (function-source-location  Signal an error if no constructor can be found."
1020       (coerce (if (consp constructor) (car constructor) constructor)    (let* ((constructor (or (kernel:dd-default-constructor dd)
1021               'function))))                            (car (kernel::dd-constructors dd))))
1022             (sym (if (consp constructor) (car constructor) constructor)))
1023        (unless sym
1024          (error "Cannot find structure's constructor: ~S" (kernel::dd-name dd)))
1025        (coerce sym 'function)))
1026    
1027    ;;;;;; Generic functions and methods
1028    
1029    (defun generic-function-definitions (name function)
1030      "Return the definitions of a generic function and its methods."
1031      (cons (list `(defgeneric ,name) (gf-location function))
1032            (gf-method-definitions function)))
1033    
1034    (defun gf-location (gf)
1035      "Return the location of the generic function GF."
1036      (definition-source-location gf (pcl::generic-function-name gf)))
1037    
1038    (defun gf-method-definitions (gf)
1039      "Return the locations of all methods of the generic function GF."
1040      (mapcar #'method-definition (pcl::generic-function-methods gf)))
1041    
1042    (defun method-definition (method)
1043      (list (method-dspec method)
1044            (method-location method)))
1045    
1046    (defun method-dspec (method)
1047      "Return a human-readable \"definition specifier\" for METHOD."
1048      (let* ((gf (pcl:method-generic-function method))
1049             (name (pcl:generic-function-name gf))
1050             (specializers (pcl:method-specializers method))
1051             (qualifiers (pcl:method-qualifiers method)))
1052        `(method ,name ,@qualifiers ,(pcl::unparse-specializers specializers))))
1053    
1054    ;; XXX maybe special case setters/getters
1055    (defun method-location (method)
1056      (function-location (or (pcl::method-fast-function method)
1057                             (pcl:method-function method))))
1058    
1059  (defun genericp (fn)  (defun genericp (fn)
1060    (typep fn 'generic-function))    (typep fn 'generic-function))
1061    
1062  (defun gf-definition-location (gf)  ;;;;;; Types and classes
1063    (flet ((guess-source-file (faslfile)  
1064             (unix-truename  (defun type-definitions (name)
1065              (merge-pathnames (make-pathname :type "lisp")    "Return `deftype' locations for type NAME."
1066                               faslfile))))    (maybe-make-definition (ext:info :type :expander name) 'deftype name))
1067      (let ((def-source (pcl::definition-source gf))  
1068            (name (string (pcl:generic-function-name gf))))  (defun maybe-make-definition (function kind name)
1069        (etypecase def-source    "If FUNCTION is non-nil then return its definition location."
1070          (pathname (make-location    (if function
1071                     `(:file ,(guess-source-file def-source))        (list (list `(,kind ,name) (function-location function)))))
1072                     `(:function-name ,name)))  
1073          (cons  (defun class-definitions (name)
1074           (destructuring-bind ((dg name) pathname) def-source    "Return the definition locations for the class called NAME."
1075             (declare (ignore dg))    (if (symbolp name)
1076             (etypecase pathname        (let ((class (kernel::find-class name nil)))
1077               (pathname          (etypecase class
1078                (make-location `(:file ,(guess-source-file pathname))            (null '())
1079                               `(:function-name ,(string name)))))))))))            (kernel::structure-class
1080               (list (list `(defstruct ,name) (dd-location (find-dd name)))))
1081  (defun method-source-location (method)            #+(or)
1082    (function-source-location (or (pcl::method-fast-function method)            (conditions::condition-class
1083                                  (pcl:method-function method))))             (list (list `(define-condition ,name)
1084                           (condition-class-location class))))
1085  (defun gf-method-locations (gf)            (kernel::standard-class
1086    (let ((ms (pcl::generic-function-methods gf)))             (list (list `(defclass ,name)
1087      (mapcar #'method-source-location ms)))                         (class-location (find-class name)))))
1088              ((or kernel::built-in-class
1089  (defun gf-source-locations (gf)                 conditions::condition-class
1090    (list* (gf-definition-location gf)                 kernel:funcallable-structure-class)
1091           (gf-method-locations gf)))             (list (list `(kernel::define-type-class ,name)
1092                           `(:error
1093  (defun function-source-locations (function)                           ,(format nil "No source info for ~A" name)))))))))
1094    "Return a list of source locations for FUNCTION."  
1095    ;; First test if FUNCTION is a closure created by defstruct; if so  (defun class-location (class)
1096    ;; extract the defstruct-description (dd) from the closure and find    "Return the `defclass' location for CLASS."
1097    ;; the constructor for the struct.  Defstruct creates a defun for    (definition-source-location class (pcl:class-name class)))
1098    ;; the default constructor and we use that as an approximation to  
1099    ;; the source location of the defstruct.  (defun find-dd (name)
1100    ;;    "Find the defstruct-definition by the name of its structure-class."
1101    ;; For an ordinary function we return the source location of the    (let ((layout (ext:info :type :compiler-layout name)))
1102    ;; first code-location we find.      (if layout
1103    (cond ((struct-closure-p function)          (kernel:layout-info layout))))
1104           (list  
1105            (safe-definition-finding  (defun condition-class-location (class)
1106             (dd-source-location (struct-closure-dd function)))))    (let ((slots (conditions::condition-class-slots class))
1107          ((genericp function)          (name (conditions::condition-class-name class)))
1108           (gf-source-locations function))      (cond ((null slots)
1109          (t             `(:error ,(format nil "No location info for condition: ~A" name)))
1110           (list            (t
1111            (multiple-value-bind (code-location error)             ;; Find the class via one of its slot-reader methods.
1112                (safe-definition-finding (function-first-code-location function))             (let* ((slot (first slots))
1113              (cond (error (list :error (princ-to-string error)))                    (gf (fdefinition
1114                    (t (code-location-source-location code-location))))))))                         (first (conditions::condition-slot-readers slot)))))
1115                 (method-location
1116  (defun function-source-location (function)                (first
1117    (destructuring-bind (first) (function-source-locations function)                 (pcl:compute-applicable-methods-using-classes
1118      first))                  gf (list (find-class name))))))))))
1119    
1120  (defslimefun find-function-locations (symbol-name)  (defun make-name-in-file-location (file string)
1121    "Return a list of source-locations for SYMBOL-NAME's functions."    (multiple-value-bind (filename c)
1122    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)        (ignore-errors
1123      (cond ((not foundp)          (unix-truename (merge-pathnames (make-pathname :type "lisp")
1124             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))                                          file)))
1125            ((macro-function symbol)      (cond (filename (make-location `(:file ,filename)
1126             (function-source-locations (macro-function symbol)))                                     `(:function-name ,(string string))))
1127            ((special-operator-p symbol)            (t (list :error (princ-to-string c))))))
1128             (list (list :error (format nil "~A is a special-operator" symbol))))  
1129            ((fboundp symbol)  (defun source-location-form-numbers (location)
1130             (function-source-locations (coerce symbol 'function)))    (c::decode-form-numbers (c::form-numbers-form-numbers location)))
1131            (t (list (list :error  
1132                           (format nil "Symbol not fbound: ~A" symbol-name))))  (defun source-location-tlf-number (location)
1133            )))    (nth-value 0 (source-location-form-numbers location)))
1134    
1135    (defun source-location-form-number (location)
1136      (nth-value 1 (source-location-form-numbers location)))
1137    
1138    (defun resolve-file-source-location (location)
1139      (let ((filename (c::file-source-location-pathname location))
1140            (tlf-number (source-location-tlf-number location))
1141            (form-number (source-location-form-number location)))
1142        (with-open-file (s filename)
1143          (let ((pos (form-number-stream-position tlf-number form-number s)))
1144            (make-location `(:file ,(unix-truename filename))
1145                           `(:position ,(1+ pos)))))))
1146    
1147    (defun resolve-stream-source-location (location)
1148      (let ((info (c::stream-source-location-user-info location))
1149            (tlf-number (source-location-tlf-number location))
1150            (form-number (source-location-form-number location)))
1151        ;; XXX duplication in frame-source-location
1152        (assert (info-from-emacs-buffer-p info))
1153        (destructuring-bind (&key emacs-buffer emacs-buffer-string
1154                                  emacs-buffer-offset) info
1155          (with-input-from-string (s emacs-buffer-string)
1156            (let ((pos (form-number-stream-position tlf-number form-number s)))
1157              (make-location `(:buffer ,emacs-buffer)
1158                             `(:offset ,emacs-buffer-offset ,pos)))))))
1159    
1160    ;; XXX predicates for 18e backward compatibilty.  Remove them when
1161    ;; we're 19a only.
1162    (defun file-source-location-p (object)
1163      (when (fboundp 'c::file-source-location-p)
1164        (c::file-source-location-p object)))
1165    
1166    (defun stream-source-location-p (object)
1167      (when (fboundp 'c::stream-source-location-p)
1168        (c::stream-source-location-p object)))
1169    
1170    (defun source-location-p (object)
1171      (or (file-source-location-p object)
1172          (stream-source-location-p object)))
1173    
1174    (defun resolve-source-location (location)
1175      (etypecase location
1176        ((satisfies file-source-location-p)
1177         (resolve-file-source-location location))
1178        ((satisfies stream-source-location-p)
1179         (resolve-stream-source-location location))))
1180    
1181    (defun definition-source-location (object name)
1182      (let ((source (pcl::definition-source object)))
1183        (etypecase source
1184          (null
1185           `(:error ,(format nil "No source info for: ~A" object)))
1186          ((satisfies source-location-p)
1187           (resolve-source-location source))
1188          (pathname
1189           (make-name-in-file-location source name))
1190          (cons
1191           (destructuring-bind ((dg name) pathname) source
1192             (declare (ignore dg))
1193             (etypecase pathname
1194               (pathname (make-name-in-file-location pathname (string name)))
1195               (null `(:error ,(format nil "Cannot resolve: ~S" source)))))))))
1196    
1197    (defun setf-definitions (name)
1198      (let ((f (or (ext:info :setf :inverse name)
1199                   (ext:info :setf :expander name)
1200                   (and (symbolp name)
1201                        (fboundp `(setf ,name))
1202                        (fdefinition `(setf ,name))))))
1203        (if f
1204            `(((setf ,name) ,(function-location (cond ((functionp  f) f)
1205                                                      ((macro-function f))
1206                                                      ((fdefinition f)))))))))
1207    
1208    (defun variable-location (symbol)
1209      (multiple-value-bind (location foundp)
1210          ;; XXX for 18e compatibilty. rewrite this when we drop 18e
1211          ;; support.
1212          (ignore-errors (eval `(ext:info :source-location :defvar ',symbol)))
1213        (if (and foundp location)
1214            (resolve-source-location location)
1215            `(:error ,(format nil "No source info for variable ~S" symbol)))))
1216    
1217    (defun variable-definitions (name)
1218      (if (symbolp name)
1219          (multiple-value-bind (kind recorded-p) (ext:info :variable :kind name)
1220            (if recorded-p
1221                (list (list `(variable ,kind ,name)
1222                            (variable-location name)))))))
1223    
1224    (defun compiler-macro-definitions (symbol)
1225      (maybe-make-definition (compiler-macro-function symbol)
1226                             'define-compiler-macro
1227                             symbol))
1228    
1229    (defun source-transform-definitions (name)
1230      (maybe-make-definition (ext:info :function :source-transform name)
1231                             'c:def-source-transform
1232                             name))
1233    
1234    (defun function-info-definitions (name)
1235      (let ((info (ext:info :function :info name)))
1236        (if info
1237            (append (loop for transform in (c::function-info-transforms info)
1238                          collect (list `(c:deftransform ,name
1239                                          ,(c::type-specifier
1240                                            (c::transform-type transform)))
1241                                        (function-location (c::transform-function
1242                                                            transform))))
1243                    (maybe-make-definition (c::function-info-derive-type info)
1244                                           'c::derive-type name)
1245                    (maybe-make-definition (c::function-info-optimizer info)
1246                                           'c::optimizer name)
1247                    (maybe-make-definition (c::function-info-ltn-annotate info)
1248                                           'c::ltn-annotate name)
1249                    (maybe-make-definition (c::function-info-ir2-convert info)
1250                                           'c::ir2-convert name)
1251                    (loop for template in (c::function-info-templates info)
1252                          collect (list `(c::vop ,(c::template-name template))
1253                                        (function-location
1254                                         (c::vop-info-generator-function
1255                                          template))))))))
1256    
1257    (defun ir1-translator-definitions (name)
1258      (maybe-make-definition (ext:info :function :ir1-convert name)
1259                             'c:def-ir1-translator name))
1260    
1261    
1262  ;;;; Documentation.  ;;;; Documentation.
1263    
1264  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
1265    (let ((result '()))    (let ((result '()))
1266      (flet ((doc (kind)      (flet ((doc (kind)
1267               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 701  The second return value is the condition Line 1274  The second return value is the condition
1274                     (declare (ignore kind))                     (declare (ignore kind))
1275                     (if (or (boundp symbol) recorded-p)                     (if (or (boundp symbol) recorded-p)
1276                         (doc 'variable))))                         (doc 'variable))))
1277        (maybe-push        (when (fboundp symbol)
1278         :generic-function          (maybe-push
1279         (if (and (fboundp symbol)           (cond ((macro-function symbol)     :macro)
1280                  (typep (fdefinition symbol) 'generic-function))                 ((special-operator-p symbol) :special-operator)
1281             (doc 'function)))                 ((genericp (fdefinition symbol)) :generic-function)
1282        (maybe-push                 (t :function))
1283         :function (if (and (fboundp symbol)           (doc 'function)))
                           (not (typep (fdefinition symbol) 'generic-function)))  
                      (doc 'function)))  
1284        (maybe-push        (maybe-push
1285         :setf (if (or (ext:info setf inverse symbol)         :setf (if (or (ext:info setf inverse symbol)
1286                       (ext:info setf expander symbol))                       (ext:info setf expander symbol))
# Line 734  The second return value is the condition Line 1305  The second return value is the condition
1305                         (doc nil)))                         (doc nil)))
1306        result)))        result)))
1307    
1308  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
1309    (print-description-to-string    (describe (ecase namespace
1310     (or (ext:info setf inverse (from-string symbol-name))                (:variable
1311         (ext:info setf expander (from-string symbol-name)))))                 symbol)
1312                  ((:function :generic-function)
1313  (defslimefun describe-type (symbol-name)                 (symbol-function symbol))
1314    (print-description-to-string                (:setf
1315     (kernel:values-specifier-type (from-string symbol-name))))                 (or (ext:info setf inverse symbol)
1316                       (ext:info setf expander symbol)))
1317  (defslimefun describe-class (symbol-name)                (:type
1318    (print-description-to-string (find-class (from-string symbol-name) nil)))                 (kernel:values-specifier-type symbol))
1319                  (:class
1320  (defslimefun describe-alien-type (symbol-name)                 (find-class symbol))
1321    (let ((name (from-string symbol-name)))                (:alien-struct
1322      (ecase (ext:info :alien-type :kind name)                 (ext:info :alien-type :struct symbol))
1323        (:primitive                (:alien-union
1324         (print-description-to-string                 (ext:info :alien-type :union symbol))
1325          (let ((alien::*values-type-okay* t))                (:alien-enum
1326            (funcall (ext:info :alien-type :translator name) (list name)))))                 (ext:info :alien-type :enum symbol))
1327        ((:defined)                (:alien-type
1328         (print-description-to-string (ext:info :alien-type :definition name)))                 (ecase (ext:info :alien-type :kind symbol)
1329        (:unknown                   (:primitive
1330         (format nil "Unkown alien type: ~A" symbol-name)))))                    (let ((alien::*values-type-okay* t))
1331                        (funcall (ext:info :alien-type :translator symbol)
1332  (defmacro %describe-alien (symbol-name namespace)                               (list symbol))))
1333    `(print-description-to-string                   ((:defined)
1334      (ext:info :alien-type ,namespace (from-string ,symbol-name))))                    (ext:info :alien-type :definition symbol))
1335                     (:unknown :unkown))))))
1336  (defslimefun describe-alien-struct (symbol-name)  
1337    (%describe-alien symbol-name :struct))  ;;;;; Argument lists
1338    
1339  (defslimefun describe-alien-union (symbol-name)  (defimplementation arglist (fun)
1340    (%describe-alien symbol-name :union))    (etypecase fun
1341        (function (function-arglist fun))
1342  (defslimefun describe-alien-enum (symbol-name)      (symbol (function-arglist (or (macro-function fun)
1343    (%describe-alien symbol-name :enum))                                    (symbol-function fun))))))
1344    
1345  (defmethod arglist-string (fname)  (defun function-arglist (fun)
1346    "Return a string describing the argument list for FNAME.    (let ((arglist
1347  The result has the format \"(...)\"."           (cond ((eval:interpreted-function-p fun)
1348    (declare (type string fname))                  (eval:interpreted-function-arglist fun))
1349    (multiple-value-bind (function condition)                 ((pcl::generic-function-p fun)
1350        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))                  (pcl:generic-function-lambda-list fun))
1351      (when condition                 ((c::byte-function-or-closure-p fun)
1352        (return-from arglist-string (format nil "(-- ~A)" condition)))                  (byte-code-function-arglist fun))
1353      (let ((arglist                 ((kernel:%function-arglist (kernel:%function-self fun))
1354             (if (not (or (fboundp function)                  (handler-case (read-arglist fun)
1355                          (functionp function)))                    (error () :not-available)))
1356                 "(-- <Unknown-Function>)"                 ;; this should work both for compiled-debug-function
1357                 (let* ((fun (or (macro-function function)                 ;; and for interpreted-debug-function
1358                                 (symbol-function function)))                 (t
1359                        (df (di::function-debug-function fun))                  (handler-case (debug-function-arglist
1360                        (arglist (kernel:%function-arglist fun)))                                 (di::function-debug-function fun))
1361                   (cond ((eval:interpreted-function-p fun)                    (di:unhandled-condition () :not-available))))))
1362                          (eval:interpreted-function-arglist fun))      (check-type arglist (or list (member :not-available)))
1363                         ((pcl::generic-function-p fun)      arglist))
1364                          (pcl::gf-pretty-arglist fun))  
1365                         (arglist arglist)  (defimplementation function-name (function)
1366                         ;; this should work both for    (cond ((eval:interpreted-function-p function)
1367                         ;; compiled-debug-function and for           (eval:interpreted-function-name function))
1368                         ;; interpreted-debug-function          ((pcl::generic-function-p function)
1369                         (df (di::debug-function-lambda-list df))           (pcl::generic-function-name function))
1370                         (t "(<arglist-unavailable>)"))))))          ((c::byte-function-or-closure-p function)
1371        (if (stringp arglist)           (c::byte-function-name function))
1372            arglist          (t (kernel:%function-name (kernel:%function-self function)))))
1373            (to-string arglist)))))  
1374    ;;; A simple case: the arglist is available as a string that we can
1375    ;;; `read'.
1376    
1377    (defun read-arglist (fn)
1378      "Parse the arglist-string of the function object FN."
1379      (let ((string (kernel:%function-arglist
1380                     (kernel:%function-self fn)))
1381            (package (find-package
1382                      (c::compiled-debug-info-package
1383                       (kernel:%code-debug-info
1384                        (vm::find-code-object fn))))))
1385        (with-standard-io-syntax
1386          (let ((*package* (or package *package*)))
1387            (read-from-string string)))))
1388    
1389    ;;; A harder case: an approximate arglist is derived from available
1390    ;;; debugging information.
1391    
1392    (defun debug-function-arglist (debug-function)
1393      "Derive the argument list of DEBUG-FUNCTION from debug info."
1394      (let ((args (di::debug-function-lambda-list debug-function))
1395            (required '())
1396            (optional '())
1397            (rest '())
1398            (key '()))
1399        ;; collect the names of debug-vars
1400        (dolist (arg args)
1401          (etypecase arg
1402            (di::debug-variable
1403             (push (di::debug-variable-symbol arg) required))
1404            ((member :deleted)
1405             (push ':deleted required))
1406            (cons
1407             (ecase (car arg)
1408               (:keyword
1409                (push (second arg) key))
1410               (:optional
1411                (push (debug-variable-symbol-or-deleted (second arg)) optional))
1412               (:rest
1413                (push (debug-variable-symbol-or-deleted (second arg)) rest))))))
1414        ;; intersperse lambda keywords as needed
1415        (append (nreverse required)
1416                (if optional (cons '&optional (nreverse optional)))
1417                (if rest (cons '&rest (nreverse rest)))
1418                (if key (cons '&key (nreverse key))))))
1419    
1420    (defun debug-variable-symbol-or-deleted (var)
1421      (etypecase var
1422        (di:debug-variable
1423         (di::debug-variable-symbol var))
1424        ((member :deleted)
1425         '#:deleted)))
1426    
1427    (defun symbol-debug-function-arglist (fname)
1428      "Return FNAME's debug-function-arglist and %function-arglist.
1429    A utility for debugging DEBUG-FUNCTION-ARGLIST."
1430      (let ((fn (fdefinition fname)))
1431        (values (debug-function-arglist (di::function-debug-function fn))
1432                (kernel:%function-arglist (kernel:%function-self fn)))))
1433    
1434    ;;; Deriving arglists for byte-compiled functions:
1435    ;;;
1436    (defun byte-code-function-arglist (fn)
1437      ;; There doesn't seem to be much arglist information around for
1438      ;; byte-code functions.  Use the arg-count and return something like
1439      ;; (arg0 arg1 ...)
1440      (etypecase fn
1441        (c::simple-byte-function
1442         (loop for i from 0 below (c::simple-byte-function-num-args fn)
1443               collect (make-arg-symbol i)))
1444        (c::hairy-byte-function
1445         (hairy-byte-function-arglist fn))
1446        (c::byte-closure
1447         (byte-code-function-arglist (c::byte-closure-function fn)))))
1448    
1449    (defun make-arg-symbol (i)
1450      (make-symbol (format nil "~A~D" (string 'arg) i)))
1451    
1452    ;;; A "hairy" byte-function is one that takes a variable number of
1453    ;;; arguments. `hairy-byte-function' is a type from the bytecode
1454    ;;; interpreter.
1455    ;;;
1456    (defun hairy-byte-function-arglist (fn)
1457      (let ((counter -1))
1458        (flet ((next-arg () (make-arg-symbol (incf counter))))
1459          (with-struct (c::hairy-byte-function- min-args max-args rest-arg-p
1460                                                keywords-p keywords) fn
1461            (let ((arglist '())
1462                  (optional (- max-args min-args)))
1463              ;; XXX isn't there a better way to write this?
1464              ;; (Looks fine to me. -luke)
1465              (dotimes (i min-args)
1466                (push (next-arg) arglist))
1467              (when (plusp optional)
1468                (push '&optional arglist)
1469                (dotimes (i optional)
1470                  (push (next-arg) arglist)))
1471              (when rest-arg-p
1472                (push '&rest arglist)
1473                (push (next-arg) arglist))
1474              (when keywords-p
1475                (push '&key arglist)
1476                (loop for (key _ __) in keywords
1477                      do (push key arglist))
1478                (when (eq keywords-p :allow-others)
1479                  (push '&allow-other-keys arglist)))
1480              (nreverse arglist))))))
1481    
1482    
1483  ;;;; Miscellaneous.  ;;;; Miscellaneous.
1484    
1485  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
1486    (walker:macroexpand-all form))    (walker:macroexpand-all form))
1487    
1488  (defun tracedp (fname)  (defimplementation compiler-macroexpand-1 (form &optional env)
1489    (gethash (debug::trace-fdefinition fname)    (ext:compiler-macroexpand-1 form env))
1490             debug::*traced-functions*))  
1491    (defimplementation compiler-macroexpand (form &optional env)
1492  (defslimefun toggle-trace-fdefinition (fname-string)    (ext:compiler-macroexpand form env))
   (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)))))  
1493    
1494  (defslimefun set-default-directory (directory)  (defimplementation set-default-directory (directory)
1495    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
1496    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
1497    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
1498    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
1499    (namestring (ext:default-directory)))    (default-directory))
1500    
1501    (defimplementation default-directory ()
1502  ;;;; Source-paths    (namestring (ext:default-directory)))
   
 ;;; 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))))))  
1503    
1504  (defun code-location-stream-position (code-location stream)  (defimplementation getpid ()
1505    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the    (unix:unix-getpid))
 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)))  
1506    
1507  (defun code-location-file-position (code-location filename)  (defimplementation lisp-implementation-type-name ()
1508    (with-open-file (s filename :direction :input)    "cmucl")
     (code-location-stream-position code-location s)))  
1509    
1510  (defun debug-source-info-from-emacs-buffer-p (debug-source)  (defimplementation quit-lisp ()
1511    (let ((info (c::debug-source-info debug-source)))    (ext::quit))
     (and info  
          (consp info)  
          (eq :emacs-buffer (car info)))))  
1512    
1513  (defun source-location-from-code-location (code-location)  ;;; source-path-{stream,file,string,etc}-position moved into
1514    "Return the source location for CODE-LOCATION."  ;;; swank-source-path-parser
   (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))))))  
   
 (defun code-location-source-location (code-location)  
   "Safe wrapper around `code-location-from-source-location'."  
   (safe-definition-finding  
    (source-location-from-code-location code-location)))  
   
 (defslimefun getpid ()  
   (unix:unix-getpid))  
1515    
1516    
1517  ;;;; Debugging  ;;;; Debugging
1518    
1519  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
1520    
1521  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
1522    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
1523    (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*))  
1524           (debug:*stack-top-hint* nil)           (debug:*stack-top-hint* nil)
1525           (*debugger-hook* nil)           (kernel:*current-level* 0))
1526           (*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  
1527                      (lambda (condition)                      (lambda (condition)
1528                        (signal (make-condition                        (error (make-condition
1529                                 'sldb-condition                                'sldb-condition
1530                                 :original-condition condition)))))                                :original-condition condition)))))
1531        (funcall debugger-loop-fn))))        (unwind-protect
1532               (progn
1533  (defun format-restarts-for-emacs ()               #+(or)(sys:scrub-control-stack)
1534    "Return a list of restarts for *swank-debugger-condition* in a               (funcall debugger-loop-fn))
1535  format suitable for Emacs."          #+(or)(sys:scrub-control-stack)
1536    (loop for restart in *sldb-restarts*          ))))
1537          collect (list (princ-to-string (restart-name restart))  
1538                        (princ-to-string restart))))  (defun frame-down (frame)
1539      (handler-case (di:frame-down frame)
1540  (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*)))  
1541    
1542  (defun nth-frame (index)  (defun nth-frame (index)
1543    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (frame-down frame))
1544         (i index (1- i)))         (i index (1- i)))
1545        ((zerop i) frame)))        ((zerop i) frame)))
1546    
1547  (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."  
1548    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
1549      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (frame-down f)
1550            for i from start below end            for i from start below end
1551            while f            while f collect f)))
1552            collect f)))  
1553    (defimplementation print-frame (frame stream)
1554      (let ((*standard-output* stream))
1555        (handler-case
1556            (debug::print-frame-call frame :verbosity 1 :number nil)
1557          (error (e)
1558            (ignore-errors (princ e stream))))))
1559    
1560    (defimplementation frame-source-location (index)
1561      (let ((frame (nth-frame index)))
1562        (cond ((foreign-frame-p frame) (foreign-frame-source-location frame))
1563              ((code-location-source-location (di:frame-code-location frame))))))
1564    
1565  (defmethod backtrace (start end)  (defimplementation eval-in-frame (form index)
1566    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (di:eval-in-frame (nth-frame index) form))
1567    
1568  (defmethod debugger-info-for-emacs (start end)  (defun frame-debug-vars (frame)
1569    (list (format-condition-for-emacs)    "Return a vector of debug-variables in frame."
1570          (format-restarts-for-emacs)    (let ((loc (di:frame-code-location frame)))
1571          (backtrace start end)))      (remove-if
1572         (lambda (v)
1573           (not (eq (di:debug-variable-validity v loc) :valid)))
1574         (di::debug-function-debug-variables (di:frame-debug-function frame)))))
1575    
1576    (defun debug-var-value (var frame)
1577      (let* ((loc (di:frame-code-location frame))
1578             (validity (di:debug-variable-validity var loc)))
1579        (ecase validity
1580          (:valid (di:debug-variable-value var frame))
1581          ((:invalid :unknown) (make-symbol (string validity))))))
1582    
1583    (defimplementation frame-locals (index)
1584      (let ((frame (nth-frame index)))
1585        (loop for v across (frame-debug-vars frame)
1586              collect (list :name (di:debug-variable-symbol v)
1587                            :id (di:debug-variable-id v)
1588                            :value (debug-var-value v frame)))))
1589    
1590    (defimplementation frame-var-value (frame var)
1591      (let* ((frame (nth-frame frame))
1592             (dvar (aref (frame-debug-vars frame) var)))
1593        (debug-var-value dvar frame)))
1594    
1595    (defimplementation frame-catch-tags (index)
1596      (mapcar #'car (di:frame-catches (nth-frame index))))
1597    
1598    (defimplementation return-from-frame (index form)
1599      (let ((sym (find-symbol (string 'find-debug-tag-for-frame)
1600                              :debug-internals)))
1601        (if sym
1602            (let* ((frame (nth-frame index))
1603                   (probe (funcall sym frame)))
1604              (cond (probe (throw (car probe) (eval-in-frame form index)))
1605                    (t (format nil "Cannot return from frame: ~S" frame))))
1606            "return-from-frame is not implemented in this version of CMUCL.")))
1607    
1608  (defmethod frame-source-location-for-emacs (index)  (defimplementation activate-stepping (frame)
1609    (code-location-source-location (di:frame-code-location (nth-frame index))))    (set-step-breakpoints (nth-frame frame)))
1610    
1611  (defmethod eval-in-frame (form index)  (defimplementation sldb-break-on-return (frame)
1612    (di:eval-in-frame (nth-frame index) form))    (break-on-return (nth-frame frame)))
1613    
1614  (defslimefun pprint-eval-string-in-frame (string index)  ;;; We set the breakpoint in the caller which might be a bit confusing.
1615    (swank-pprint  ;;;
1616     (multiple-value-list  (defun break-on-return (frame)
1617      (di:eval-in-frame (nth-frame index) (from-string string)))))    (let* ((caller (di:frame-down frame))
1618             (cl (di:frame-code-location caller)))
1619  (defslimefun inspect-in-frame (string index)      (flet ((hook (frame bp)
1620    (reset-inspector)               (when (frame-pointer= frame caller)
1621    (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))                 (di:delete-breakpoint bp)
1622                   (signal-breakpoint bp frame))))
1623  (defmethod frame-locals (index)        (let* ((info (ecase (di:code-location-kind cl)
1624    (let* ((frame (nth-frame index))                       ((:single-value-return :unknown-return) nil)
1625           (location (di:frame-code-location frame))                       (:known-return (debug-function-returns
1626           (debug-function (di:frame-debug-function frame))                                       (di:frame-debug-function frame)))))
1627           (debug-variables (di::debug-function-debug-variables debug-function)))               (bp (di:make-breakpoint #'hook cl :kind :code-location
1628      (loop for v across debug-variables                                       :info info)))
1629            collect (list          (di:activate-breakpoint bp)
1630                     :symbol (di:debug-variable-symbol v)          `(:ok ,(format nil "Set breakpoint in ~A" caller))))))
1631                     :id (di:debug-variable-id v)  
1632                     :value-string  (defun frame-pointer= (frame1 frame2)
1633                     (if (eq (di:debug-variable-validity v location)    "Return true if the frame pointers of FRAME1 and FRAME2 are the same."
1634                             :valid)    (sys:sap= (di::frame-pointer frame1) (di::frame-pointer frame2)))
1635                         (to-string (di:debug-variable-value v frame))  
1636                         "<not-available>")))))  ;;; The PC in escaped frames at a single-return-value point is
1637    ;;; actually vm:single-value-return-byte-offset bytes after the
1638  (defmethod frame-catch-tags (index)  ;;; position given in the debug info.  Here we try to recognize such
1639    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  ;;; cases.
1640          collect `(,tag . ,(code-location-source-location code-location))))  ;;;
1641    (defun next-code-locations (frame code-location)
1642      "Like `debug::next-code-locations' but be careful in escaped frames."
1643      (let ((next (debug::next-code-locations code-location)))
1644        (flet ((adjust-pc ()
1645                 (let ((cl (di::copy-compiled-code-location code-location)))
1646                   (incf (di::compiled-code-location-pc cl)
1647                         vm:single-value-return-byte-offset)
1648                   cl)))
1649          (cond ((and (di::compiled-frame-escaped frame)
1650                      (eq (di:code-location-kind code-location)
1651                          :single-value-return)
1652                      (= (length next) 1)
1653                      (di:code-location= (car next) (adjust-pc)))
1654                 (debug::next-code-locations (car next)))
1655                (t
1656                 next)))))
1657    
1658    (defun set-step-breakpoints (frame)
1659      (let ((cl (di:frame-code-location frame)))
1660        (when (di:debug-block-elsewhere-p (di:code-location-debug-block cl))
1661          (error "Cannot step in elsewhere code"))
1662        (let* ((debug::*bad-code-location-types*
1663                (remove :call-site debug::*bad-code-location-types*))
1664               (next (next-code-locations frame cl)))
1665          (cond (next
1666                 (let ((steppoints '()))
1667                   (flet ((hook (bp-frame bp)
1668                            (signal-breakpoint bp bp-frame)
1669                            (mapc #'di:delete-breakpoint steppoints)))
1670                     (dolist (code-location next)
1671                       (let ((bp (di:make-breakpoint #'hook code-location
1672                                                     :kind :code-location)))
1673                         (di:activate-breakpoint bp)
1674                         (push bp steppoints))))))
1675                (t
1676                 (break-on-return frame))))))
1677    
1678    
1679    ;; XXX the return values at return breakpoints should be passed to the
1680    ;; user hooks. debug-int.lisp should be changed to do this cleanly.
1681    
1682    ;;; The sigcontext and the PC for a breakpoint invocation are not
1683    ;;; passed to user hook functions, but we need them to extract return
1684    ;;; values. So we advice di::handle-breakpoint and bind the values to
1685    ;;; special variables.
1686    ;;;
1687    (defvar *breakpoint-sigcontext*)
1688    (defvar *breakpoint-pc*)
1689    
1690    ;; XXX don't break old versions without fwrappers.  Remove this one day.
1691    #+#.(cl:if (cl:find-package :fwrappers) '(and) '(or))
1692    (progn
1693      (fwrappers:define-fwrapper bind-breakpoint-sigcontext (offset c sigcontext)
1694        (let ((*breakpoint-sigcontext* sigcontext)
1695              (*breakpoint-pc* offset))
1696          (fwrappers:call-next-function)))
1697      (fwrappers:set-fwrappers 'di::handle-breakpoint '())
1698      (fwrappers:fwrap 'di::handle-breakpoint #'bind-breakpoint-sigcontext))
1699    
1700    (defun sigcontext-object (sc index)
1701      "Extract the lisp object in sigcontext SC at offset INDEX."
1702      (kernel:make-lisp-obj (vm:sigcontext-register sc index)))
1703    
1704    (defun known-return-point-values (sigcontext sc-offsets)
1705      (let ((fp (system:int-sap (vm:sigcontext-register sigcontext
1706                                                        vm::cfp-offset))))
1707        (system:without-gcing
1708         (loop for sc-offset across sc-offsets
1709               collect (di::sub-access-debug-var-slot fp sc-offset sigcontext)))))
1710    
1711    ;;; CMUCL returns the first few values in registers and the rest on
1712    ;;; the stack. In the multiple value case, the number of values is
1713    ;;; stored in a dedicated register. The values of the registers can be
1714    ;;; accessed in the sigcontext for the breakpoint.  There are 3 kinds
1715    ;;; of return conventions: :single-value-return, :unknown-return, and
1716    ;;; :known-return.
1717    ;;;
1718    ;;; The :single-value-return convention returns the value in a
1719    ;;; register without setting the nargs registers.
1720    ;;;
1721    ;;; The :unknown-return variant is used for multiple values. A
1722    ;;; :unknown-return point consists actually of 2 breakpoints: one for
1723    ;;; the single value case and one for the general case.  The single
1724    ;;; value breakpoint comes vm:single-value-return-byte-offset after
1725    ;;; the multiple value breakpoint.
1726    ;;;
1727    ;;; The :known-return convention is used by local functions.
1728    ;;; :known-return is currently not supported because we don't know
1729    ;;; where the values are passed.
1730    ;;;
1731    (defun breakpoint-values (breakpoint)
1732      "Return the list of return values for a return point."
1733      (flet ((1st (sc) (sigcontext-object sc (car vm::register-arg-offsets))))
1734        (let ((sc (locally (declare (optimize (speed 0)))
1735                    (alien:sap-alien *breakpoint-sigcontext* (* unix:sigcontext))))
1736              (cl (di:breakpoint-what breakpoint)))
1737          (ecase (di:code-location-kind cl)
1738            (:single-value-return
1739             (list (1st sc)))
1740            (:known-return
1741             (let ((info (di:breakpoint-info breakpoint)))
1742               (if (vectorp info)
1743                   (known-return-point-values sc info)
1744                   (progn
1745                     ;;(break)
1746                     (list "<<known-return convention not supported>>" info)))))
1747            (:unknown-return
1748             (let ((mv-return-pc (di::compiled-code-location-pc cl)))
1749               (if (= mv-return-pc *breakpoint-pc*)
1750                   (mv-function-end-breakpoint-values sc)
1751                   (list (1st sc)))))))))
1752    
1753    ;; XXX: di::get-function-end-breakpoint-values takes 2 arguments in
1754    ;; newer versions of CMUCL (after ~March 2005).
1755    (defun mv-function-end-breakpoint-values (sigcontext)
1756      (let ((sym (find-symbol "FUNCTION-END-BREAKPOINT-VALUES/STANDARD" :di)))
1757        (cond (sym (funcall sym sigcontext))
1758              (t (funcall 'di::get-function-end-breakpoint-values sigcontext)))))
1759    
1760    (defun debug-function-returns (debug-fun)
1761      "Return the return style of DEBUG-FUN."
1762      (let* ((cdfun (di::compiled-debug-function-compiler-debug-fun debug-fun)))
1763        (c::compiled-debug-function-returns cdfun)))
1764    
1765    (define-condition breakpoint (simple-condition)
1766      ((message :initarg :message :reader breakpoint.message)
1767       (values  :initarg :values  :reader breakpoint.values))
1768      (:report (lambda (c stream) (princ (breakpoint.message c) stream))))
1769    
1770    (defimplementation condition-extras (condition)
1771      (typecase condition
1772        (breakpoint
1773         ;; pop up the source buffer
1774         `((:show-frame-source 0)))
1775        (t '())))
1776    
1777    (defun signal-breakpoint (breakpoint frame)
1778      "Signal a breakpoint condition for BREAKPOINT in FRAME.
1779    Try to create a informative message."
1780      (flet ((brk (values fstring &rest args)
1781               (let ((msg (apply #'format nil fstring args))
1782                     (debug:*stack-top-hint* frame))
1783                 (break 'breakpoint :message msg :values values))))
1784        (with-struct (di::breakpoint- kind what) breakpoint
1785          (case kind
1786            (:code-location
1787             (case (di:code-location-kind what)
1788               ((:single-value-return :known-return :unknown-return)
1789                (let ((values (breakpoint-values breakpoint)))
1790                  (brk values "Return value: ~{~S ~}" values)))
1791               (t
1792                #+(or)
1793                (when (eq (di:code-location-kind what) :call-site)
1794                  (call-site-function breakpoint frame))
1795                (brk nil "Breakpoint: ~S ~S"
1796                     (di:code-location-kind what)
1797                     (di::compiled-code-location-pc what)))))
1798            (:function-start
1799             (brk nil "Function start breakpoint"))
1800            (t (brk nil "Breakpoint: ~A in ~A" breakpoint frame))))))
1801    
1802    (defimplementation sldb-break-at-start (fname)
1803      (let ((debug-fun (di:function-debug-function (coerce fname 'function))))
1804        (cond ((not debug-fun)
1805               `(:error ,(format nil "~S has no debug-function" fname)))
1806              (t
1807               (flet ((hook (frame bp &optional args cookie)
1808                        (declare (ignore args cookie))
1809                        (signal-breakpoint bp frame)))
1810                 (let ((bp (di:make-breakpoint #'hook debug-fun
1811                                               :kind :function-start)))
1812                   (di:activate-breakpoint bp)
1813                   `(:ok ,(format nil "Set breakpoint in ~S" fname))))))))
1814    
1815    (defun frame-cfp (frame)
1816      "Return the Control-Stack-Frame-Pointer for FRAME."
1817      (etypecase frame
1818        (di::compiled-frame (di::frame-pointer frame))
1819        ((or di::interpreted-frame null) -1)))
1820    
1821    (defun frame-ip (frame)
1822      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1823      (if (not frame)
1824          -1
1825          (let ((debug-fun (di::frame-debug-function frame)))
1826            (etypecase debug-fun
1827              (di::compiled-debug-function
1828               (let* ((code-loc (di:frame-code-location frame))
1829                      (component (di::compiled-debug-function-component debug-fun))
1830                      (pc (di::compiled-code-location-pc code-loc))
1831                      (ip (sys:without-gcing
1832                           (sys:sap-int
1833                            (sys:sap+ (kernel:code-instructions component) pc)))))
1834                 (values ip pc)))
1835              (di::interpreted-debug-function -1)
1836              (di::bogus-debug-function
1837               #-x86 -1
1838               #+x86
1839               (let ((fp (di::frame-pointer (di:frame-up frame))))
1840                 (multiple-value-bind (ra ofp) (di::x86-call-context fp)
1841                   (declare (ignore ofp))
1842                   (values ra 0))))))))
1843    
1844    (defun frame-registers (frame)
1845      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1846      (let* ((cfp (frame-cfp frame))
1847             (csp (frame-cfp (di::frame-up frame)))
1848             (ip (frame-ip frame))
1849             (ocfp (frame-cfp (di::frame-down frame)))
1850             (lra (frame-ip (di::frame-down frame))))
1851        (values csp cfp ip ocfp lra)))
1852    
1853    (defun print-frame-registers (frame-number)
1854      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1855        (flet ((fixnum (p) (etypecase p
1856                             (integer p)
1857                             (sys:system-area-pointer (sys:sap-int p)))))
1858          (apply #'format t "~
1859    ~8X  Stack Pointer
1860    ~8X  Frame Pointer
1861    ~8X  Instruction Pointer
1862    ~8X  Saved Frame Pointer
1863    ~8X  Saved Instruction Pointer~%" (mapcar #'fixnum
1864                          (multiple-value-list (frame-registers frame)))))))
1865    
1866    (defvar *gdb-program-name* "/usr/bin/gdb")
1867    
1868    (defimplementation disassemble-frame (frame-number)
1869      (print-frame-registers frame-number)
1870      (terpri)
1871      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1872             (debug-fun (di::frame-debug-function frame)))
1873        (etypecase debug-fun
1874          (di::compiled-debug-function
1875           (let* ((component (di::compiled-debug-function-component debug-fun))
1876                  (fun (di:debug-function-function debug-fun)))
1877             (if fun
1878                 (disassemble fun)
1879                 (disassem:disassemble-code-component component))))
1880          (di::bogus-debug-function
1881           (cond ((probe-file *gdb-program-name*)
1882                  (let ((ip (sys:sap-int (frame-ip frame))))
1883                    (princ (gdb-command "disas 0x~x" ip))))
1884                 (t
1885                  (format t "~%[Disassembling bogus frames not implemented]")))))))
1886    
1887  (defslimefun invoke-nth-restart (index)  (defmacro with-temporary-file ((stream filename) &body body)
1888    (invoke-restart-interactively (nth-restart index)))    `(call/temporary-file (lambda (,stream ,filename) . ,body)))
1889    
1890    (defun call/temporary-file (fun)
1891      (let ((name (system::pick-temporary-file-name)))
1892        (unwind-protect
1893             (with-open-file (stream name :direction :output :if-exists :supersede)
1894               (funcall fun stream name))
1895          (delete-file name))))
1896    
1897    (defun gdb-command (format-string &rest args)
1898      (let ((str (gdb-exec (format nil "attach ~d~%~a~%detach"
1899                                   (getpid)
1900                                   (apply #'format nil format-string args)))))
1901        (subseq str (1+ (position #\newline str)))))
1902    
1903    (defun gdb-exec (cmd)
1904      (with-temporary-file (file filename)
1905        (write-string cmd file)
1906        (force-output file)
1907        (let* ((output (make-string-output-stream))
1908               (proc (ext:run-program "gdb" `("-batch" "-x" ,filename)
1909                                      :wait t
1910                                      :output output)))
1911          (assert (eq (ext:process-status proc) :exited))
1912          (assert (eq (ext:process-exit-code proc) 0))
1913          (get-output-stream-string output))))
1914    
1915    (defun foreign-frame-p (frame)
1916      #-x86 nil
1917      #+x86 (let ((ip (frame-ip frame)))
1918              (and (sys:system-area-pointer-p ip)
1919                   (multiple-value-bind (pc code)
1920                       (di::compute-lra-data-from-pc ip)
1921                     (declare (ignore pc))
1922                     (not code)))))
1923    
1924    (defun foreign-frame-source-location (frame)
1925      (let ((ip (sys:sap-int (frame-ip frame))))
1926        (cond ((probe-file *gdb-program-name*)
1927               (parse-gdb-line-info (gdb-command "info line *0x~x" ip)))
1928              (t `(:error "no srcloc available for ~a" frame)))))
1929    
1930    ;; The output of gdb looks like:
1931    ;; Line 215 of "../../src/lisp/x86-assem.S"
1932    ;;    starts at address 0x805318c <Ldone+11>
1933    ;;    and ends at 0x805318e <Ldone+13>.
1934    ;; The ../../ are fixed up with the "target:" search list which might
1935    ;; be wrong sometimes.
1936    (defun parse-gdb-line-info (string)
1937      (with-input-from-string (*standard-input* string)
1938        (let ((w1 (read-word)))
1939          (cond ((equal w1 "Line")
1940                 (let ((line (read-word)))
1941                   (assert (equal (read-word) "of"))
1942                   (let ((file (read-word)))
1943                     (make-location (list :file
1944                                          (unix-truename
1945                                           (merge-pathnames
1946                                            (read-from-string file)
1947                                            (format nil "~a/lisp/"
1948                                                    (unix-truename "target:")))))
1949                                    (list :line (parse-integer line))))))
1950                (t `(:error ,string))))))
1951    
1952    (defun read-word (&optional (stream *standard-input*))
1953      (peek-char t stream)
1954      (concatenate 'string (loop until (whitespacep (peek-char nil stream))
1955                                 collect (read-char stream))))
1956    
1957  (defslimefun sldb-abort ()  (defun whitespacep (char)
1958    (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))    (member char '(#\space #\newline)))
1959    
1960    
1961  ;;;; Inspecting  ;;;; Inspecting
1962    
 (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))))))  
1963  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1964    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1965      vm:function-pointer-type      vm:function-pointer-type
# Line 1152  stack." Line 1968  stack."
1968      vm:odd-fixnum-type      vm:odd-fixnum-type
1969      vm:instance-pointer-type      vm:instance-pointer-type
1970      vm:other-immediate-1-type      vm:other-immediate-1-type
1971      vm:other-pointer-type))      vm:other-pointer-type)
1972      "Names of the constants that specify type tags.
1973    The `symbol-value' of each element is a type tag.")
1974    
1975  (defconstant +header-type-symbols+  (defconstant +header-type-symbols+
1976    ;; Is there a convinient place for all those constants?    (labels ((suffixp (suffix string)
1977    (flet ((tail-comp (string tail)               (and (>= (length string) (length suffix))
1978             (and (>= (length string) (length tail))                    (string= string suffix :start1 (- (length string)
1979                  (string= string tail :start1 (- (length string)                                                      (length suffix)))))
1980                                                  (length tail))))))             (header-type-symbol-p (x)
1981      (remove-if-not               (and (suffixp "-TYPE" (symbol-name x))
1982       (lambda (x) (and (tail-comp (symbol-name x) "-TYPE")                    (not (member x +lowtag-symbols+))
1983                        (not (member x +lowtag-symbols+))                    (boundp x)
1984                        (boundp x)                    (typep (symbol-value x) 'fixnum))))
1985                        (typep (symbol-value x) 'fixnum)))      (remove-if-not #'header-type-symbol-p
1986       (append (apropos-list "-TYPE" "VM" t)                     (append (apropos-list "-TYPE" "VM")
1987               (apropos-list "-TYPE" "BIGNUM" t)))))                             (apropos-list "-TYPE" "BIGNUM"))))
1988      "A list of names of the type codes in boxed objects.")
1989    
1990  (defun describe-primitive-type (object)  (defimplementation describe-primitive-type (object)
1991    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1992      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1993             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1994        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1995        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1996                                    vm:function-pointer-type                                   vm:function-pointer-type
1997                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
1998                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
1999                                    ))                                   ))
2000               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
2001                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
2002                                         :key #'symbol-value)))                                    :key #'symbol-value)))
2003                 (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."))  
2004    
2005  (defmethod inspected-parts (o)  (defmethod emacs-inspect ((o t))
2006    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
2007           (inspected-parts-of-value-cell o))           `("Value: " (:value ,(c:value-cell-ref o))))
2008            ((alien::alien-value-p o)
2009             (inspect-alien-value o))
2010          (t          (t
2011           (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.~%")))))))  
2012    
2013  (defmethod inspected-parts ((o function))  (defun cmucl-inspect (o)
2014      (destructuring-bind (text labeledp . parts) (inspect::describe-parts o)
2015        (list* (format nil "~A~%" text)
2016               (if labeledp
2017                   (loop for (label . value) in parts
2018                         append (label-value-line label value))
2019                   (loop for value in parts  for i from 0
2020                         append (label-value-line i value))))))
2021    
2022    (defmethod emacs-inspect ((o function))
2023    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
2024      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
2025             (values             (append (label-value-line*
2026              (format nil "~A~% is a function." o)                      ("Self" (kernel:%function-self o))
2027              (list (cons "Self" (kernel:%function-self o))                      ("Next" (kernel:%function-next o))
2028                    (cons "Next" (kernel:%function-next o))                      ("Name" (kernel:%function-name o))
2029                    (cons "Name" (kernel:%function-name o))                      ("Arglist" (kernel:%function-arglist o))
2030                    (cons "Arglist" (kernel:%function-arglist o))                      ("Type" (kernel:%function-type o))
2031                    (cons "Type" (kernel:%function-type o))                      ("Code" (kernel:function-code-header o)))
2032                    (cons "Code Object" (kernel:function-code-header o)))))                     (list
2033            ((= header vm:closure-header-type)                      (with-output-to-string (s)
2034             (values (format nil "~A~% is a closure." o)                        (disassem:disassemble-function o :stream s)))))
2035                     (list*            ((= header vm:closure-header-type)
2036                      (cons "Function" (kernel:%closure-function o))             (list* (format nil "~A is a closure.~%" o)
2037                      (loop for i from 0 below (- (kernel:get-closure-length o)                    (append
2038                                                  (1- vm:closure-info-offset))                     (label-value-line "Function" (kernel:%closure-function o))
2039                            collect (cons (format nil "~D" i)                     `("Environment:" (:newline))
2040                                          (kernel:%closure-index-ref o i))))))                     (loop for i from 0 below (1- (kernel:get-closure-length o))
2041            (t (call-next-method o)))))                           append (label-value-line
2042                                     i (kernel:%closure-index-ref o i))))))
2043  (defmethod inspected-parts ((o kernel:code-component))            ((eval::interpreted-function-p o)
2044    (values (format nil "~A~% is a code data-block." o)             (cmucl-inspect o))
2045            `(("First entry point" . ,(kernel:%code-entry-points o))            (t
2046              ,@(loop for i from vm:code-constants-offset             (call-next-method)))))
2047                      below (kernel:get-header-data o)  
2048                      collect (cons (format nil "Constant#~D" i)  (defmethod emacs-inspect ((o kernel:funcallable-instance))
2049                                    (kernel:code-header-ref o i)))    (append (label-value-line*
2050              ("Debug info" . ,(kernel:%code-debug-info o))             (:function (kernel:%funcallable-instance-function o))
2051              ("Instructions"  . ,(kernel:code-instructions o)))))             (:lexenv  (kernel:%funcallable-instance-lexenv o))
2052               (:layout  (kernel:%funcallable-instance-layout o)))
2053  (defmethod inspected-parts ((o kernel:fdefn))            (cmucl-inspect o)))
2054    (values (format nil "~A~% is a fdefn object." o)  
2055            `(("Name" . ,(kernel:fdefn-name o))  (defmethod emacs-inspect ((o kernel:code-component))
2056              ("Function" . ,(kernel:fdefn-function o)))))    (append
2057       (label-value-line*
2058  ;;; Local Variables:      ("code-size" (kernel:%code-code-size o))
2059  ;;; 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))
2060  ;;; End:      ("debug-info" (kernel:%code-debug-info o))
2061        ("trace-table-offset" (kernel:code-header-ref
2062                               o vm:code-trace-table-offset-slot)))
2063       `("Constants:" (:newline))
2064       (loop for i from vm:code-constants-offset
2065             below (kernel:get-header-data o)
2066             append (label-value-line i (kernel:code-header-ref o i)))
2067       `("Code:"
2068         (:newline)
2069         , (with-output-to-string (*standard-output*)
2070             (cond ((c::compiled-debug-info-p (kernel:%code-debug-info o))
2071                    (disassem:disassemble-code-component o))
2072                   ((or
2073                     (c::debug-info-p (kernel:%code-debug-info o))
2074                     (consp (kernel:code-header-ref
2075                             o vm:code-trace-table-offset-slot)))
2076                    (c:disassem-byte-component o))
2077                   (t
2078                    (disassem:disassemble-memory
2079                     (disassem::align
2080                      (+ (logandc2 (kernel:get-lisp-obj-address o)
2081                                   vm:lowtag-mask)
2082                         (* vm:code-constants-offset vm:word-bytes))
2083                      (ash 1 vm:lowtag-bits))
2084                     (ash (kernel:%code-code-size o) vm:word-shift))))))))
2085    
2086    (defmethod emacs-inspect ((o kernel:fdefn))
2087      (label-value-line*
2088       ("name" (kernel:fdefn-name o))
2089       ("function" (kernel:fdefn-function o))
2090       ("raw-addr" (sys:sap-ref-32
2091                    (sys:int-sap (kernel:get-lisp-obj-address o))
2092                    (* vm:fdefn-raw-addr-slot vm:word-bytes)))))
2093    
2094    #+(or)
2095    (defmethod emacs-inspect ((o array))
2096      (if (typep o 'simple-array)
2097          (call-next-method)
2098          (label-value-line*
2099           (:header (describe-primitive-type o))
2100           (:rank (array-rank o))
2101           (:fill-pointer (kernel:%array-fill-pointer o))
2102           (:fill-pointer-p (kernel:%array-fill-pointer-p o))
2103           (:elements (kernel:%array-available-elements o))
2104           (:data (kernel:%array-data-vector o))
2105           (:displacement (kernel:%array-displacement o))
2106           (:displaced-p (kernel:%array-displaced-p o))
2107           (:dimensions (array-dimensions o)))))
2108    
2109    (defmethod emacs-inspect ((o simple-vector))
2110      (append
2111       (label-value-line*
2112        (:header (describe-primitive-type o))
2113        (:length (c::vector-length o)))
2114       (loop for i below (length o)
2115             append (label-value-line i (aref o i)))))
2116    
2117    (defun inspect-alien-record (alien)
2118      (with-struct (alien::alien-value- sap type) alien
2119        (with-struct (alien::alien-record-type- kind name fields) type
2120          (append
2121           (label-value-line*
2122            (:sap sap)
2123            (:kind kind)
2124            (:name name))
2125           (loop for field in fields
2126                 append (let ((slot (alien::alien-record-field-name field)))
2127                          (declare (optimize (speed 0)))
2128                          (label-value-line slot (alien:slot alien slot))))))))
2129    
2130    (defun inspect-alien-pointer (alien)
2131      (with-struct (alien::alien-value- sap type) alien
2132        (label-value-line*
2133         (:sap sap)
2134         (:type type)
2135         (:to (alien::deref alien)))))
2136    
2137    (defun inspect-alien-value (alien)
2138      (typecase (alien::alien-value-type alien)
2139        (alien::alien-record-type (inspect-alien-record alien))
2140        (alien::alien-pointer-type (inspect-alien-pointer alien))
2141        (t (cmucl-inspect alien))))
2142    
2143    ;;;; Profiling
2144    (defimplementation profile (fname)
2145      (eval `(profile:profile ,fname)))
2146    
2147    (defimplementation unprofile (fname)
2148      (eval `(profile:unprofile ,fname)))
2149    
2150    (defimplementation unprofile-all ()
2151      (eval `(profile:unprofile))
2152      "All functions unprofiled.")
2153    
2154    (defimplementation profile-report ()
2155      (eval `(profile:report-time)))
2156    
2157    (defimplementation profile-reset ()
2158      (eval `(profile:reset-time))
2159      "Reset profiling counters.")
2160    
2161    (defimplementation profiled-functions ()
2162      profile:*timed-functions*)
2163    
2164    (defimplementation profile-package (package callers methods)
2165      (profile:profile-all :package package
2166                           :callers-p callers
2167                           #-cmu18e :methods #-cmu18e methods))
2168    
2169    
2170    ;;;; Multiprocessing
2171    
2172    #+mp
2173    (progn
2174      (defimplementation initialize-multiprocessing (continuation)
2175        (mp::init-multi-processing)
2176        (mp:make-process continuation :name "swank")
2177        ;; Threads magic: this never returns! But top-level becomes
2178        ;; available again.
2179        (unless mp::*idle-process*
2180          (mp::startup-idle-and-top-level-loops)))
2181    
2182      (defimplementation spawn (fn &key name)
2183        (mp:make-process fn :name (or name "Anonymous")))
2184    
2185      (defvar *thread-id-counter* 0)
2186    
2187      (defimplementation thread-id (thread)
2188        (or (getf (mp:process-property-list thread) 'id)
2189            (setf (getf (mp:process-property-list thread) 'id)
2190                  (incf *thread-id-counter*))))
2191    
2192      (defimplementation find-thread (id)
2193        (find id (all-threads)
2194              :key (lambda (p) (getf (mp:process-property-list p) 'id))))
2195    
2196      (defimplementation thread-name (thread)
2197        (mp:process-name thread))
2198    
2199      (defimplementation thread-status (thread)
2200        (mp:process-whostate thread))
2201    
2202      (defimplementation current-thread ()
2203        mp:*current-process*)
2204    
2205      (defimplementation all-threads ()
2206        (copy-list mp:*all-processes*))
2207    
2208      (defimplementation interrupt-thread (thread fn)
2209        (mp:process-interrupt thread fn))
2210    
2211      (defimplementation kill-thread (thread)
2212        (mp:destroy-process thread))
2213    
2214      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
2215    
2216      (defstruct (mailbox (:conc-name mailbox.))
2217        (mutex (mp:make-lock "process mailbox"))
2218        (queue '() :type list))
2219    
2220      (defun mailbox (thread)
2221        "Return THREAD's mailbox."
2222        (mp:with-lock-held (*mailbox-lock*)
2223          (or (getf (mp:process-property-list thread) 'mailbox)
2224              (setf (getf (mp:process-property-list thread) 'mailbox)
2225                    (make-mailbox)))))
2226    
2227      (defimplementation send (thread message)
2228        (check-slime-interrupts)
2229        (let* ((mbox (mailbox thread)))
2230          (mp:with-lock-held ((mailbox.mutex mbox))
2231            (setf (mailbox.queue mbox)
2232                  (nconc (mailbox.queue mbox) (list message))))))
2233    
2234      (defimplementation receive-if (test &optional timeout)
2235        (let ((mbox (mailbox mp:*current-process*)))
2236          (assert (or (not timeout) (eq timeout t)))
2237          (loop
2238           (check-slime-interrupts)
2239           (mp:with-lock-held ((mailbox.mutex mbox))
2240             (let* ((q (mailbox.queue mbox))
2241                    (tail (member-if test q)))
2242               (when tail
2243                 (setf (mailbox.queue mbox)
2244                       (nconc (ldiff q tail) (cdr tail)))
2245                 (return (car tail)))))
2246           (when (eq timeout t) (return (values nil t)))
2247           (mp:process-wait-with-timeout
2248            "receive-if" 0.5
2249            (lambda () (some test (mailbox.queue mbox)))))))
2250    
2251    
2252      ) ;; #+mp
2253    
2254    
2255    
2256    ;;;; GC hooks
2257    ;;;
2258    ;;; Display GC messages in the echo area to avoid cluttering the
2259    ;;; normal output.
2260    ;;;
2261    
2262    ;; this should probably not be here, but where else?
2263    (defun background-message (message)
2264      (funcall (find-symbol (string :background-message) :swank)
2265               message))
2266    
2267    (defun print-bytes (nbytes &optional stream)
2268      "Print the number NBYTES to STREAM in KB, MB, or GB units."
2269      (let ((names '((0 bytes) (10 kb) (20 mb) (30 gb) (40 tb) (50 eb))))
2270        (multiple-value-bind (power name)
2271            (loop for ((p1 n1) (p2 n2)) on names
2272                  while n2 do
2273                  (when (<= (expt 2 p1) nbytes (1- (expt 2 p2)))
2274                    (return (values p1 n1))))
2275          (cond (name
2276                 (format stream "~,1F ~A" (/ nbytes (expt 2 power)) name))
2277                (t
2278                 (format stream "~:D bytes" nbytes))))))
2279    
2280    (defconstant gc-generations 6)
2281    
2282    #+gencgc
2283    (defun generation-stats ()
2284      "Return a string describing the size distribution among the generations."
2285      (let* ((alloc (loop for i below gc-generations
2286                          collect (lisp::gencgc-stats i)))
2287             (sum (coerce (reduce #'+ alloc) 'float)))
2288        (format nil "~{~3F~^/~}"
2289                (mapcar (lambda (size) (/ size sum))
2290                        alloc))))
2291    
2292    (defvar *gc-start-time* 0)
2293    
2294    (defun pre-gc-hook (bytes-in-use)
2295      (setq *gc-start-time* (get-internal-real-time))
2296      (let ((msg (format nil "[Commencing GC with ~A in use.]"
2297                         (print-bytes bytes-in-use))))
2298        (background-message msg)))
2299    
2300    (defun post-gc-hook (bytes-retained bytes-freed trigger)
2301      (declare (ignore trigger))
2302      (let* ((seconds (/ (- (get-internal-real-time) *gc-start-time*)
2303                         internal-time-units-per-second))
2304             (msg (format nil "[GC done. ~A freed  ~A retained  ~A  ~4F sec]"
2305                         (print-bytes bytes-freed)
2306                         (print-bytes bytes-retained)
2307                         #+gencgc(generation-stats)
2308                         #-gencgc""
2309                         seconds)))
2310        (background-message msg)))
2311    
2312    (defun install-gc-hooks ()
2313      (setq ext:*gc-notify-before* #'pre-gc-hook)
2314      (setq ext:*gc-notify-after* #'post-gc-hook))
2315    
2316    (defun remove-gc-hooks ()
2317      (setq ext:*gc-notify-before* #'lisp::default-gc-notify-before)
2318      (setq ext:*gc-notify-after* #'lisp::default-gc-notify-after))
2319    
2320    (defvar *install-gc-hooks* t
2321      "If non-nil install GC hooks")
2322    
2323    (defimplementation emacs-connected ()
2324      (when *install-gc-hooks*
2325        (install-gc-hooks)))
2326    
2327    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2328    ;;Trace implementations
2329    ;;In CMUCL, we have:
2330    ;; (trace <name>)
2331    ;; (trace (method <name> <qualifier>? (<specializer>+)))
2332    ;; (trace :methods t '<name>) ;;to trace all methods of the gf <name>
2333    ;; <name> can be a normal name or a (setf name)
2334    
2335    (defun tracedp (spec)
2336      (member spec (eval '(trace)) :test #'equal))
2337    
2338    (defun toggle-trace-aux (spec &rest options)
2339      (cond ((tracedp spec)
2340             (eval `(untrace ,spec))
2341             (format nil "~S is now untraced." spec))
2342            (t
2343             (eval `(trace ,spec ,@options))
2344             (format nil "~S is now traced." spec))))
2345    
2346    (defimplementation toggle-trace (spec)
2347      (ecase (car spec)
2348        ((setf)
2349         (toggle-trace-aux spec))
2350        ((:defgeneric)
2351         (let ((name (second spec)))
2352           (toggle-trace-aux name :methods name)))
2353        ((:defmethod)
2354         (cond ((fboundp `(method ,@(cdr spec)))
2355                (toggle-trace-aux `(method ,(cdr spec))))
2356               ;; Man, is this ugly
2357               ((fboundp `(pcl::fast-method ,@(cdr spec)))
2358                (toggle-trace-aux `(pcl::fast-method ,@(cdr spec))))
2359               (t
2360                (error 'undefined-function :name (cdr spec)))))
2361        ((:call)
2362         (destructuring-bind (caller callee) (cdr spec)
2363           (toggle-trace-aux (process-fspec callee)
2364                             :wherein (list (process-fspec caller)))))
2365        ;; doesn't work properly
2366        ;; ((:labels :flet) (toggle-trace-aux (process-fspec spec)))
2367        ))
2368    
2369    (defun process-fspec (fspec)
2370      (cond ((consp fspec)
2371             (ecase (first fspec)
2372               ((:defun :defgeneric) (second fspec))
2373               ((:defmethod)
2374                `(method ,(second fspec) ,@(third fspec) ,(fourth fspec)))
2375               ((:labels) `(labels ,(third fspec) ,(process-fspec (second fspec))))
2376               ((:flet) `(flet ,(third fspec) ,(process-fspec (second fspec))))))
2377            (t
2378             fspec)))
2379    
2380    ;;; Weak datastructures
2381    
2382    (defimplementation make-weak-key-hash-table (&rest args)
2383      (apply #'make-hash-table :weak-p t args))
2384    
2385    
2386    ;;; Save image
2387    
2388    (defimplementation save-image (filename &optional restart-function)
2389      (multiple-value-bind (pid error) (unix:unix-fork)
2390        (when (not pid) (error "fork: ~A" (unix:get-unix-error-msg error)))
2391        (cond ((= pid 0)
2392               (apply #'ext:save-lisp
2393                      filename
2394                      (if restart-function
2395                          `(:init-function ,restart-function))))
2396              (t
2397               (let ((status (waitpid pid)))
2398                 (destructuring-bind (&key exited? status &allow-other-keys) status
2399                   (assert (and exited? (equal status 0)) ()
2400                           "Invalid exit status: ~a" status)))))))
2401    
2402    (defun waitpid (pid)
2403      (alien:with-alien ((status c-call:int))
2404        (let ((code (alien:alien-funcall
2405                     (alien:extern-alien
2406                      waitpid (alien:function c-call:int c-call:int
2407                                              (* c-call:int) c-call:int))
2408                     pid (alien:addr status) 0)))
2409          (cond ((= code -1) (error "waitpid: ~A" (unix:get-unix-error-msg)))
2410                (t (assert (= code pid))
2411                   (decode-wait-status status))))))
2412    
2413    (defun decode-wait-status (status)
2414      (let ((output (with-output-to-string (s)
2415                      (call-program (list (process-status-program)
2416                                          (format nil "~d" status))
2417                                    :output s))))
2418        (read-from-string output)))
2419    
2420    (defun call-program (args &key output)
2421      (destructuring-bind (program &rest args) args
2422        (let ((process (ext:run-program program args :output output)))
2423          (when (not program) (error "fork failed"))
2424          (unless (and (eq (ext:process-status process) :exited)
2425                       (= (ext:process-exit-code process) 0))
2426            (error "Non-zero exit status")))))
2427    
2428    (defvar *process-status-program* nil)
2429    
2430    (defun process-status-program ()
2431      (or *process-status-program*
2432          (setq *process-status-program*
2433                (compile-process-status-program))))
2434    
2435    (defun compile-process-status-program ()
2436      (let ((infile (system::pick-temporary-file-name
2437                     "/tmp/process-status~d~c.c")))
2438        (with-open-file (stream infile :direction :output :if-exists :supersede)
2439          (format stream "
2440    #include <stdio.h>
2441    #include <stdlib.h>
2442    #include <sys/types.h>
2443    #include <sys/wait.h>
2444    #include <assert.h>
2445    
2446    #define FLAG(value) (value ? \"t\" : \"nil\")
2447    
2448    int main (int argc, char** argv) {
2449      assert (argc == 2);
2450      {
2451        char* endptr = NULL;
2452        char* arg = argv[1];
2453        long int status = strtol (arg, &endptr, 10);
2454        assert (endptr != arg && *endptr == '\\0');
2455        printf (\"(:exited? %s :status %d :signal? %s :signal %d :coredump? %s\"
2456                \" :stopped? %s :stopsig %d)\\n\",
2457                FLAG(WIFEXITED(status)), WEXITSTATUS(status),
2458                FLAG(WIFSIGNALED(status)), WTERMSIG(status),
2459                FLAG(WCOREDUMP(status)),
2460                FLAG(WIFSTOPPED(status)), WSTOPSIG(status));
2461        fflush (NULL);
2462        return 0;
2463      }
2464    }
2465    ")
2466          (finish-output stream))
2467        (let* ((outfile (system::pick-temporary-file-name))
2468               (args (list "cc" "-o" outfile infile)))
2469          (warn "Running cc: ~{~a ~}~%" args)
2470          (call-program args :output t)
2471          (delete-file infile)
2472          outfile)))
2473    
2474    ;; (save-image "/tmp/x.core")
2475    
2476    ;; Local Variables:
2477    ;; pbook-heading-regexp:    "^;;;\\(;+\\)"
2478    ;; pbook-commentary-regexp: "^;;;\\($\\|[^;]\\)"
2479    ;; End:

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

  ViewVC Help
Powered by ViewVC 1.1.5