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

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

  ViewVC Help
Powered by ViewVC 1.1.5