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

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

  ViewVC Help
Powered by ViewVC 1.1.5