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

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

  ViewVC Help
Powered by ViewVC 1.1.5