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

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

  ViewVC Help
Powered by ViewVC 1.1.5