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

Removed from v.1.32  
changed lines
  Added in v.1.149

  ViewVC Help
Powered by ViewVC 1.1.5