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

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

  ViewVC Help
Powered by ViewVC 1.1.5