/[slime]/slime/swank-cmucl.lisp
ViewVC logotype

Diff of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

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

  ViewVC Help
Powered by ViewVC 1.1.5