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

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

  ViewVC Help
Powered by ViewVC 1.1.5