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

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

  ViewVC Help
Powered by ViewVC 1.1.5