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

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

  ViewVC Help
Powered by ViewVC 1.1.5