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

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

  ViewVC Help
Powered by ViewVC 1.1.5