/[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.89 by heller, Thu Mar 18 21:55:07 2004 UTC
# Line 1  Line 1 
1  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
2    
3  (declaim (optimize debug))  (declaim (optimize (debug 2)))
4    
5  (in-package :swank)  (in-package :swank-backend)
6    
7  ;; Turn on xref. [should we?]  (in-package :lisp)
 (setf c:*record-xref-info* t)  
8    
9  (defun without-interrupts* (body)  ;; Fix for read-sequence in 18e
10    (sys:without-interrupts (funcall body)))  #+cmu18e
11    (progn
12      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
13        (when s
14          (setf (symbol-value s) nil)))
15    
16      (defun read-into-simple-string (s stream start end)
17        (declare (type simple-string s))
18        (declare (type stream stream))
19        (declare (type index start end))
20        (unless (subtypep (stream-element-type stream) 'character)
21          (error 'type-error
22                 :datum (read-char stream nil #\Null)
23                 :expected-type (stream-element-type stream)
24                 :format-control "Trying to read characters from a binary stream."))
25        ;; Let's go as low level as it seems reasonable.
26        (let* ((numbytes (- end start))
27               (total-bytes 0))
28          ;; read-n-bytes may return fewer bytes than requested, so we need
29          ;; to keep trying.
30          (loop while (plusp numbytes) do
31                (let ((bytes-read (system:read-n-bytes stream s start numbytes nil)))
32                  (when (zerop bytes-read)
33                    (return-from read-into-simple-string total-bytes))
34                  (incf total-bytes bytes-read)
35                  (incf start bytes-read)
36                  (decf numbytes bytes-read)))
37          total-bytes))
38    
39      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
40        (when s
41          (setf (symbol-value s) t)))
42    
43      )
44    
45    (in-package :swank-backend)
46    
47    
48    ;;;; TCP server.
49    
50    (defimplementation preferred-communication-style ()
51      :sigio)
52    
53    (defimplementation create-socket (host port)
54      (ext:create-inet-listener port :stream
55                                :reuse-address t
56                                :host (resolve-hostname host)))
57    
58    (defimplementation local-port (socket)
59      (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
60    
61    (defimplementation close-socket (socket)
62      (ext:close-socket (socket-fd socket)))
63    
64    (defimplementation accept-connection (socket)
65      #+MP (mp:process-wait-until-fd-usable socket :input)
66      (make-socket-io-stream (ext:accept-tcp-connection socket)))
67    
68    (defvar *sigio-handlers* '()
69      "List of (key . (fn . args)) pairs to be called on SIGIO.")
70    
71    (defun sigio-handler (signal code scp)
72      (declare (ignore signal code scp))
73      (mapc (lambda (handler) (funcall (cdr handler))) *sigio-handlers*))
74    
75    (defun set-sigio-handler ()
76      (sys:enable-interrupt unix:SIGIO (lambda (signal code scp)
77                                         (sigio-handler signal code scp))))
78    
79    (defun fcntl (fd command arg)
80      (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
81        (cond (ok)
82              (t (error "fcntl: ~A" (unix:get-unix-error-msg error))))))
83    
84    (defimplementation add-sigio-handler (socket fn)
85      (set-sigio-handler)
86      (let ((fd (socket-fd socket)))
87        (format *debug-io* "; Adding input handler: ~S ~%" fd)
88        (fcntl fd unix:f-setown (unix:unix-getpid))
89        (fcntl fd unix:f-setfl unix:FASYNC)
90        (push (cons fd fn) *sigio-handlers*)))
91    
92    (defimplementation remove-sigio-handlers (socket)
93      (let ((fd (socket-fd socket)))
94        (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car))
95        (sys:invalidate-descriptor fd))
96      (close socket))
97    
98    (defimplementation add-fd-handler (socket fn)
99      (let ((fd (socket-fd socket)))
100        (format *debug-io* "; Adding fd handler: ~S ~%" fd)
101        (sys:add-fd-handler fd :input (lambda (_)
102                                        _
103                                        (funcall fn)))))
104    
105    (defimplementation remove-fd-handlers (socket)
106      (sys:invalidate-descriptor (socket-fd socket)))
107    
108    (defimplementation make-fn-streams (input-fn output-fn)
109      (let* ((output (make-slime-output-stream output-fn))
110             (input  (make-slime-input-stream input-fn output)))
111        (values input output)))
112    
113    ;;;;; Socket helpers.
114    
115    (defun socket-fd (socket)
116      "Return the filedescriptor for the socket represented by SOCKET."
117      (etypecase socket
118        (fixnum socket)
119        (sys:fd-stream (sys:fd-stream-fd socket))))
120    
121    (defun resolve-hostname (hostname)
122      "Return the IP address of HOSTNAME as an integer."
123      (let* ((hostent (ext:lookup-host-entry hostname))
124             (address (car (ext:host-entry-addr-list hostent))))
125        (ext:htonl address)))
126    
127    (defun make-socket-io-stream (fd)
128      "Create a new input/output fd-stream for FD."
129      (sys:make-fd-stream fd :input t :output t :element-type 'base-char))
130    
131  (defun set-fd-non-blocking (fd)  (defun set-fd-non-blocking (fd)
132    (flet ((fcntl (fd cmd arg)    (flet ((fcntl (fd cmd arg)
133             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)             (multiple-value-bind (flags errno) (unix:unix-fcntl fd cmd arg)
134               (or flags               (or flags
135                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))                   (error "fcntl: ~A" (unix:get-unix-error-msg errno))))))
136      (let ((flags (fcntl fd unix:F-GETFL 0)))      (let ((flags (fcntl fd unix:F-GETFL 0)))
137        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))        (fcntl fd unix:F-SETFL (logior flags unix:O_NONBLOCK)))))
138    
139    
140  ;;;; TCP server.  ;;;; Unix signals
141    
142  (defun resolve-hostname (name)  (defmethod call-without-interrupts (fn)
143    (let* ((hostent (ext:lookup-host-entry name))    (sys:without-interrupts (funcall fn)))
          (address (car (ext:host-entry-addr-list hostent))))  
     (ext:htonl address)))  
144    
145  (defun create-swank-server (port &key (reuse-address t)  (defimplementation getpid ()
146                              (address "localhost"))    (unix:unix-getpid))
147    "Create a SWANK TCP server."  
148    (let* ((ip (resolve-hostname address))  (defimplementation lisp-implementation-type-name ()
149           (fd (ext:create-inet-listener port :stream    "cmucl")
150                                         :reuse-address reuse-address  
151                                         :host ip)))  (defimplementation set-default-directory (directory)
152      (system:add-fd-handler fd :input #'accept-connection)    (setf (ext:default-directory) directory)
153      (nth-value 1 (ext::get-socket-host-and-port fd))))    (namestring (setf *default-pathname-defaults* (ext:default-directory))))
   
 (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))  
154    
155    
156  ;;;; Stream handling  ;;;; Stream handling
157    
158  (defstruct (slime-output-stream  (defstruct (slime-output-stream
159               (:include lisp::lisp-stream               (:include lisp::lisp-stream
160                         (lisp::misc #'sos/misc)                         (lisp::misc #'sos/misc)
161                         (lisp::out #'sos/out)                         (lisp::out #'sos/out)
162                         (lisp::sout #'sos/sout))                         (lisp::sout #'sos/sout))
163               (:conc-name sos.)               (:conc-name sos.)
164               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
165                 (:constructor make-slime-output-stream (output-fn)))
166      (output-fn nil :type function)
167    (buffer (make-string 512) :type string)    (buffer (make-string 512) :type string)
168    (index 0 :type kernel:index)    (index 0 :type kernel:index)
169    (column 0 :type kernel:index))    (column 0 :type kernel:index))
# Line 117  The request is read from the socket as a Line 187  The request is read from the socket as a
187  (defun sos/sout (stream string start end)  (defun sos/sout (stream string start end)
188    (loop for i from start below end    (loop for i from start below end
189          do (sos/out stream (aref string i))))          do (sos/out stream (aref string i))))
190    
191  (defun sos/misc (stream operation &optional arg1 arg2)  (defun sos/misc (stream operation &optional arg1 arg2)
192    (declare (ignore arg1 arg2))    (declare (ignore arg1 arg2))
193    (case operation    (case operation
194      ((:force-output :finish-output)      ((:force-output :finish-output)
195       (let ((end (sos.index stream)))       (let ((end (sos.index stream)))
196         (unless (zerop end)         (unless (zerop end)
197           (send-to-emacs `(:read-output ,(subseq (sos.buffer stream) 0 end)))           (funcall (sos.output-fn stream) (subseq (sos.buffer stream) 0 end))
198           (setf (sos.index stream) 0))))           (setf (sos.index stream) 0))))
199      (:charpos (sos.column stream))      (:charpos (sos.column stream))
200      (:line-length 75)      (:line-length 75)
201      (:file-position nil)      (:file-position nil)
# Line 135  The request is read from the socket as a Line 205  The request is read from the socket as a
205      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
206    
207  (defstruct (slime-input-stream  (defstruct (slime-input-stream
208               (:include string-stream               (:include string-stream
209                         (lisp::in #'sis/in)                         (lisp::in #'sis/in)
210                         (lisp::misc #'sis/misc))                         (lisp::misc #'sis/misc))
211               (:conc-name sis.)               (:conc-name sis.)
212               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
213    (buffer "" :type string)               (:constructor make-slime-input-stream (input-fn sos)))
214    (index 0 :type kernel:index))    (input-fn nil :type function)
215      ;; We know our sibling output stream, so that we can force it before
216      ;; requesting input.
217      (sos      nil :type slime-output-stream)
218      (buffer   ""  :type string)
219      (index    0   :type kernel:index))
220    
221  (defun sis/in (stream eof-errorp eof-value)  (defun sis/in (stream eof-errorp eof-value)
222    (declare (ignore eof-errorp eof-value))    (declare (ignore eof-errorp eof-value))
223    (let ((index (sis.index stream))    (let ((index (sis.index stream))
224          (buffer (sis.buffer stream)))          (buffer (sis.buffer stream)))
225      (when (= index (length buffer))      (when (= index (length buffer))
226        (setf buffer (slime-read-string))        (force-output (sis.sos stream))
227          (setf buffer (funcall (sis.input-fn stream)))
228        (setf (sis.buffer stream) buffer)        (setf (sis.buffer stream) buffer)
229        (setf index 0))        (setf index 0))
230      (prog1 (aref buffer index)      (prog1 (aref buffer index)
# Line 162  The request is read from the socket as a Line 238  The request is read from the socket as a
238      (:unread (setf (aref (sis.buffer stream)      (:unread (setf (aref (sis.buffer stream)
239                           (decf (sis.index stream)))                           (decf (sis.index stream)))
240                     arg1))                     arg1))
241      (:clear-input (setf (sis.index stream) 0      (:clear-input
242         (setf (sis.index stream) 0
243                          (sis.buffer stream) ""))                          (sis.buffer stream) ""))
244      (:listen (< (sis.index stream) (length (sis.buffer stream))))      (:listen (< (sis.index stream) (length (sis.buffer stream))))
245      (:charpos nil)      (:charpos nil)
# Line 174  The request is read from the socket as a Line 251  The request is read from the socket as a
251    
252  ;;;; Compilation Commands  ;;;; Compilation Commands
253    
 (defvar *swank-source-info* nil  
   "Bound to a SOURCE-INFO object during compilation.")  
   
254  (defvar *previous-compiler-condition* nil  (defvar *previous-compiler-condition* nil
255    "Used to detect duplicates.")    "Used to detect duplicates.")
256    
257  (defvar *previous-context* nil  (defvar *previous-context* nil
258    "Previous compiler error context.")    "Previous compiler error context.")
259    
 (defvar *compiler-notes* '()  
   "List of compiler notes for the last compilation unit.")  
   
260  (defvar *buffer-name* nil)  (defvar *buffer-name* nil)
261  (defvar *buffer-start-position* nil)  (defvar *buffer-start-position* nil)
262  (defvar *buffer-substring* nil)  (defvar *buffer-substring* nil)
 (defvar *compile-filename* nil)  
263    
264    
265  ;;;;; Trapping notes  ;;;;; Trapping notes
# Line 201  C:*COMPILER-NOTIFICATION-FUNCTION*. The Line 271  C:*COMPILER-NOTIFICATION-FUNCTION*. The
271  craft our own error messages, which can omit a lot of redundant  craft our own error messages, which can omit a lot of redundant
272  information."  information."
273    (unless (eq condition *previous-compiler-condition*)    (unless (eq condition *previous-compiler-condition*)
274      (let ((context (or (c::find-error-context nil) *previous-context*)))      (let ((context (c::find-error-context nil)))
275        (setq *previous-compiler-condition* condition)        (setq *previous-compiler-condition* condition)
276        (setq *previous-context* context)        (setq *previous-context* context)
277        (signal-compiler-condition condition context))))        (signal-compiler-condition condition context))))
# Line 211  information." Line 281  information."
281             'compiler-condition             'compiler-condition
282             :original-condition condition             :original-condition condition
283             :severity (severity-for-emacs condition)             :severity (severity-for-emacs condition)
284             :message (brief-compiler-message-for-emacs condition context)             :short-message (brief-compiler-message-for-emacs condition)
285               :message (long-compiler-message-for-emacs condition context)
286             :location (compiler-note-location context))))             :location (compiler-note-location context))))
287    
288  (defun severity-for-emacs (condition)  (defun severity-for-emacs (condition)
# Line 221  information." Line 292  information."
292      (c::style-warning :note)      (c::style-warning :note)
293      (c::warning :warning)))      (c::warning :warning)))
294    
295  (defun brief-compiler-message-for-emacs (condition error-context)  (defun brief-compiler-message-for-emacs (condition)
296    "Briefly describe a compiler error for Emacs.    "Briefly describe a compiler error for Emacs.
297  When Emacs presents the message it already has the source popped up  When Emacs presents the message it already has the source popped up
298  and the source form highlighted. This makes much of the information in  and the source form highlighted. This makes much of the information in
299  the error-context redundant."  the error-context redundant."
300      (princ-to-string condition))
301    
302    (defun long-compiler-message-for-emacs (condition error-context)
303      "Describe a compiler error for Emacs including context information."
304    (declare (type (or c::compiler-error-context null) error-context))    (declare (type (or c::compiler-error-context null) error-context))
305    (multiple-value-bind (enclosing source)    (multiple-value-bind (enclosing source)
306        (if error-context        (if error-context
# Line 234  the error-context redundant." Line 309  the error-context redundant."
309      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"
310              enclosing source condition)))              enclosing source condition)))
311    
   
312  (defun compiler-note-location (context)  (defun compiler-note-location (context)
313    (cond (context    (cond (context
314           (resolve-note-location           (resolve-note-location
# Line 270  the error-context redundant." Line 344  the error-context redundant."
344                                    (pos (eql nil))                                    (pos (eql nil))
345                                    (path (eql nil))                                    (path (eql nil))
346                                    (source (eql nil)))                                    (source (eql nil)))
347    (cond (buffer    (list :error "No error location available"))
348           (make-location (list :buffer buffer)  
349                          (list :position *buffer-start-position*)))  (defimplementation call-with-compilation-hooks (function)
350          (*compile-file-truename*    (let ((*previous-compiler-condition* nil)
351           (make-location (list :file (namestring *compile-file-truename*))          (*previous-context* nil)
352                          (list :position 0)))          (*print-readably* nil))
         (*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))  
353      (handler-bind ((c::compiler-error #'handle-notification-condition)      (handler-bind ((c::compiler-error #'handle-notification-condition)
354                     (c::style-warning  #'handle-notification-condition)                     (c::style-warning  #'handle-notification-condition)
355                     (c::warning        #'handle-notification-condition))                     (c::warning        #'handle-notification-condition))
356        ,@body)))        (funcall function))))
357    
358  (defmethod compile-file-for-emacs (filename load-p)  (defimplementation swank-compile-file (filename load-p)
359    (clear-xref-info filename)    (clear-xref-info filename)
360    (with-compilation-hooks ()    (with-compilation-hooks ()
361      (let ((*buffer-name* nil)      (let ((*buffer-name* nil))
362            (*compile-filename* filename))        (compile-file filename :load load-p))))
         (compile-file filename :load load-p))))  
363    
364  (defmethod compile-string-for-emacs (string &key buffer position)  (defimplementation swank-compile-string (string &key buffer position)
365    (with-compilation-hooks ()    (with-compilation-hooks ()
366      (let ((*package* *buffer-package*)      (let ((*buffer-name* buffer)
           (*compile-filename* nil)  
           (*buffer-name* buffer)  
367            (*buffer-start-position* position)            (*buffer-start-position* position)
368            (*buffer-substring* string))            (*buffer-substring* string))
369        (with-input-from-string (stream string)        (with-input-from-string (stream string)
# Line 315  the error-context redundant." Line 376  the error-context redundant."
376    
377  ;;;; XREF  ;;;; XREF
378    
379  (defun lookup-xrefs (finder name)  (defmacro defxref (name function)
380    (xref-results-for-emacs (funcall finder (from-string name))))    `(defimplementation ,name (name)
381        (xref-results (,function name))))
382  (defslimefun who-calls (function-name)  
383    "Return the places where FUNCTION-NAME is called."  (defxref who-calls      xref:who-calls)
384    (lookup-xrefs #'xref:who-calls function-name))  (defxref who-references xref:who-references)
385    (defxref who-binds      xref:who-binds)
386  (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))  
387    
388  #+cmu19  #+cmu19
389  (progn  (progn
390    (defslimefun who-macroexpands (macro)    (defxref who-macroexpands xref:who-macroexpands)
391      "Return the places where MACRO is expanded."    ;; XXX
392      (lookup-xrefs #'xref:who-macroexpands macro))    (defimplementation who-specializes (symbol)
393        (let* ((methods (xref::who-specializes (find-class symbol)))
394    (defslimefun who-specializes (class)             (locations (mapcar #'method-location methods)))
395      "Return the methods with specializers for CLASS."        (mapcar #'list methods locations))))
396      (let* ((methods (xref::who-specializes (find-class (from-string class))))  
397             (locations (mapcar #'method-source-location methods)))  (defun xref-results (contexts)
398        (group-xrefs (mapcar (lambda (m l)    (mapcar (lambda (xref)
399                               (cons (let ((*print-pretty* nil))              (list (xref:xref-context-name xref)
400                                       (to-string m))                    (resolve-xref-location xref)))
401                                     l))            contexts))
                            methods locations))))  
   )  
402    
403  (defun resolve-xref-location (xref)  (defun resolve-xref-location (xref)
404    (let ((name (xref:xref-context-name xref))    (let ((name (xref:xref-context-name xref))
# Line 366  the error-context redundant." Line 415  the error-context redundant."
415             `(:error ,(format nil "Unkown source location: ~S ~S ~S "             `(:error ,(format nil "Unkown source location: ~S ~S ~S "
416                               name file source-path))))))                               name file source-path))))))
417    
   
 (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))))  
   
418  (defun clear-xref-info (namestring)  (defun clear-xref-info (namestring)
419    "Clear XREF notes pertaining to FILENAME.    "Clear XREF notes pertaining to NAMESTRING.
420  This is a workaround for a CMUCL bug: XREF records are cumulative."  This is a workaround for a CMUCL bug: XREF records are cumulative."
421    (let ((filename (parse-namestring namestring)))    (when c:*record-xref-info*
422      (when c:*record-xref-info*      (let ((filename (truename namestring)))
423        (dolist (db (list xref::*who-calls*        (dolist (db (list xref::*who-calls*
424                          #+cmu19 xref::*who-is-called*                          #+cmu19 xref::*who-is-called*
425                          #+cmu19 xref::*who-macroexpands*                          #+cmu19 xref::*who-macroexpands*
# Line 415  This is a workaround for a CMUCL bug: XR Line 427  This is a workaround for a CMUCL bug: XR
427                          xref::*who-binds*                          xref::*who-binds*
428                          xref::*who-sets*))                          xref::*who-sets*))
429          (maphash (lambda (target contexts)          (maphash (lambda (target contexts)
430                       ;; XXX update during traversal?
431                     (setf (gethash target db)                     (setf (gethash target db)
432                           (delete-if                           (delete filename contexts
433                            (lambda (ctx)                                   :key #'xref:xref-context-file
434                              (xref-context-derived-from-p ctx filename))                                   :test #'equalp)))
                           contexts)))  
435                   db)))))                   db)))))
436    
 (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)))  
   
437  (defun unix-truename (pathname)  (defun unix-truename (pathname)
438    (ext:unix-namestring (truename pathname)))    (ext:unix-namestring (truename pathname)))
439    
# Line 499  constant pool." Line 503  constant pool."
503      (map-caller-code-components function spaces      (map-caller-code-components function spaces
504                                  (lambda (code) (push code referrers)))                                  (lambda (code) (push code referrers)))
505      referrers))      referrers))
506    
507  (defun debug-info-definitions (debug-info)  (defun debug-info-definitions (debug-info)
508    "Return the defintions for a debug-info.  This should only be used    "Return the defintions for a debug-info.  This should only be used
509  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 516  code (are theree others?)"
516      (destructuring-bind (first) source      (destructuring-bind (first) source
517        (ecase (c::debug-source-from first)        (ecase (c::debug-source-from first)
518          (:file          (:file
519           (list           (list (list name
520            (cons name                       (make-location
521                  (make-location                        (list :file (unix-truename (c::debug-source-name first)))
522                   (list :file (unix-truename (c::debug-source-name first)))                        (list :function-name name)))))))))
                  (list :function-name name)))))))))  
523    
524  (defun code-component-entry-points (code)  (defun code-component-entry-points (code)
525    "Return a list ((NAME . LOCATION) ...) of function definitons for    "Return a list ((NAME LOCATION) ...) of function definitons for
526  the code omponent CODE."  the code omponent CODE."
527    (delete-duplicates    (delete-duplicates
528     (loop for e = (kernel:%code-entry-points code)     (loop for e = (kernel:%code-entry-points code)
529           then (kernel::%function-next e)           then (kernel::%function-next e)
530           while e           while e
531           collect (cons (to-string (kernel:%function-name e))           collect (list (kernel:%function-name e)
532                         (function-source-location e)))                         (function-location e)))
533     :test #'equal))     :test #'equal))
534    
535  (defslimefun list-callers (symbol-name)  (defimplementation list-callers (symbol)
536    "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."    "Return a list ((NAME LOCATION) ...) of callers."
537    (let ((components (function-callers (from-string symbol-name)))    (let ((components (function-callers symbol))
538          (xrefs '()))          (xrefs '()))
539      (dolist (code components)      (dolist (code components)
540        (let* ((entry (kernel:%code-entry-points code))        (let* ((entry (kernel:%code-entry-points code))
# Line 541  the code omponent CODE." Line 544  the code omponent CODE."
544                         (debug-info-definitions                         (debug-info-definitions
545                          (kernel:%code-debug-info code)))))                          (kernel:%code-debug-info code)))))
546          (setq xrefs (nconc defs xrefs))))          (setq xrefs (nconc defs xrefs))))
547      (group-xrefs xrefs)))      xrefs))
   
548    
549  (defslimefun list-callees (symbol-name)  (defimplementation list-callees (symbol)
550    (let ((fns (function-callees (from-string symbol-name))))    (let ((fns (function-callees symbol)))
551      (group-xrefs (mapcar (lambda (fn)      (mapcar (lambda (fn)
552                             (cons (to-string (kernel:%function-name fn))                (list (kernel:%function-name fn)
553                                   (function-source-location fn)))                      (function-location fn)))
554                           fns))))              fns)))
555    
556    
557  ;;;; Definitions  ;;;; Definitions
558    
559  (defvar *debug-definition-finding* t  (defvar *debug-definition-finding* nil
560    "When true don't handle errors while looking for definitions.    "When true don't handle errors while looking for definitions.
561  This is useful when debugging the definition-finding code.")  This is useful when debugging the definition-finding code.")
562    
563  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
564    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY ignoring errors.  Return the source location returned
565  returned by BODY or if an error occurs a description of the error.  by BODY or if an error occurs a description of the error.  The second
566  The second return value is the condition or nil."  return value is the condition or nil."
567    `(flet ((body () ,@body))    `(flet ((body () ,@body))
568      (if *debug-definition-finding*      (if *debug-definition-finding*
569          (body)          (body)
570          (handler-case (values (progn ,@body) nil)          (handler-case (values (progn ,@body) nil)
571            (error (c) (values (list :error (princ-to-string c)) c))))))            (error (c) (values (list :error (princ-to-string c)) c))))))
572    
573  (defun function-first-code-location (function)  (defun function-first-code-location (function)
574    (and (function-has-debug-function-p function)    (and (function-has-debug-function-p function)
575         (di:debug-function-start-location         (di:debug-function-start-location
# Line 580  The second return value is the condition Line 583  The second return value is the condition
583             (vm::find-code-object function))             (vm::find-code-object function))
584         (not (eq closure function))))         (not (eq closure function))))
585    
586    (defun genericp (fn)
587      (typep fn 'generic-function))
588    
589  (defun struct-closure-p (function)  (defun struct-closure-p (function)
590    (or (function-code-object= function #'kernel::structure-slot-accessor)    (or (function-code-object= function #'kernel::structure-slot-accessor)
591        (function-code-object= function #'kernel::structure-slot-setter)        (function-code-object= function #'kernel::structure-slot-setter)
# Line 598  The second return value is the condition Line 604  The second return value is the condition
604              function)))              function)))
605      (kernel:layout-info (find-layout function))))      (kernel:layout-info (find-layout function))))
606    
607  (defun dd-source-location (dd)  (defun dd-location (dd)
608    (let ((constructor (or (kernel:dd-default-constructor dd)    (let ((constructor (or (kernel:dd-default-constructor dd)
609                           (car (kernel::dd-constructors dd)))))                           (car (kernel::dd-constructors dd)))))
610      (when (or (not constructor) (and (consp constructor)      (when (or (not constructor) (and (consp constructor)
611                                       (not (car constructor))))                                       (not (car constructor))))
612        (error "Cannot locate struct without constructor: ~S"        (error "Cannot locate struct without constructor: ~S"
613               (kernel::dd-name dd)))               (kernel::dd-name dd)))
614      (function-source-location      (function-location
615       (coerce (if (consp constructor) (car constructor) constructor)       (coerce (if (consp constructor) (car constructor) constructor)
616               'function))))               'function))))
617    
618  (defun genericp (fn)  (defun function-location (function)
619    (typep fn 'generic-function))    "Return the source location for FUNCTION."
   
 (defun gf-definition-location (gf)  
   (flet ((guess-source-file (faslfile)  
            (unix-truename  
             (merge-pathnames (make-pathname :type "lisp")  
                              faslfile))))  
     (let ((def-source (pcl::definition-source gf))  
           (name (string (pcl:generic-function-name gf))))  
       (etypecase def-source  
         (pathname (make-location  
                    `(:file ,(guess-source-file def-source))  
                    `(:function-name ,name)))  
         (cons  
          (destructuring-bind ((dg name) pathname) def-source  
            (declare (ignore dg))  
            (etypecase pathname  
              (pathname  
               (make-location `(:file ,(guess-source-file pathname))  
                              `(:function-name ,(string name)))))))))))  
   
 (defun method-source-location (method)  
   (function-source-location (or (pcl::method-fast-function method)  
                                 (pcl:method-function method))))  
   
 (defun gf-method-locations (gf)  
   (let ((ms (pcl::generic-function-methods gf)))  
     (mapcar #'method-source-location ms)))  
   
 (defun gf-source-locations (gf)  
   (list* (gf-definition-location gf)  
          (gf-method-locations gf)))  
   
 (defun function-source-locations (function)  
   "Return a list of source locations for FUNCTION."  
620    ;; First test if FUNCTION is a closure created by defstruct; if so    ;; First test if FUNCTION is a closure created by defstruct; if so
621    ;; extract the defstruct-description (dd) from the closure and find    ;; extract the defstruct-description (dd) from the closure and find
622    ;; the constructor for the struct.  Defstruct creates a defun for    ;; the constructor for the struct.  Defstruct creates a defun for
# Line 654  The second return value is the condition Line 626  The second return value is the condition
626    ;; For an ordinary function we return the source location of the    ;; For an ordinary function we return the source location of the
627    ;; first code-location we find.    ;; first code-location we find.
628    (cond ((struct-closure-p function)    (cond ((struct-closure-p function)
629           (list           (safe-definition-finding
630            (safe-definition-finding            (dd-location (struct-closure-dd function))))
            (dd-source-location (struct-closure-dd function)))))  
631          ((genericp function)          ((genericp function)
632           (gf-source-locations function))           (gf-location function))
633          (t          (t
634           (list           (multiple-value-bind (code-location error)
635            (multiple-value-bind (code-location error)               (safe-definition-finding (function-first-code-location function))
636                (safe-definition-finding (function-first-code-location function))             (cond (error (list :error (princ-to-string error)))
637              (cond (error (list :error (princ-to-string error)))                   (t (code-location-source-location code-location)))))))
638                    (t (code-location-source-location code-location))))))))  
639    (defun method-location (method)
640  (defun function-source-location (function)    (function-location (or (pcl::method-fast-function method)
641    (destructuring-bind (first) (function-source-locations function)                           (pcl:method-function method))))
642      first))  
643    (defun method-dspec (method)
644  (defslimefun find-function-locations (symbol-name)    (let* ((gf (pcl:method-generic-function method))
645    "Return a list of source-locations for SYMBOL-NAME's functions."           (name (pcl:generic-function-name gf))
646    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)           (specializers (pcl:method-specializers method)))
647      (cond ((not foundp)      `(method ,name ,(pcl::unparse-specializers specializers))))
648             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))  
649            ((macro-function symbol)  (defun method-definition (method)
650             (function-source-locations (macro-function symbol)))    (list (method-dspec method)
651            ((special-operator-p symbol)          (method-location method)))
652             (list (list :error (format nil "~A is a special-operator" symbol))))  
653            ((fboundp symbol)  (defun make-name-in-file-location (file string)
654             (function-source-locations (coerce symbol 'function)))    (multiple-value-bind (filename c)
655            (t (list (list :error        (ignore-errors (unix-truename
656                           (format nil "Symbol not fbound: ~A" symbol-name))))                        (merge-pathnames (make-pathname :type "lisp")
657            )))                                         file)))
658        (cond (filename (make-location `(:file ,filename)
659                                       `(:function-name ,string)))
660              (t (list :error (princ-to-string c))))))
661    
662    (defun gf-location (gf)
663      (let ((def-source (pcl::definition-source gf))
664            (name (string (nth-value 1 (ext:valid-function-name-p
665                                        (pcl:generic-function-name gf))))))
666        (etypecase def-source
667          (pathname (make-name-in-file-location def-source name))
668          (cons
669           (destructuring-bind ((dg name) pathname) def-source
670             (declare (ignore dg))
671             (etypecase pathname
672               (pathname (make-name-in-file-location pathname (string name)))
673               (null `(:error ,(format nil "Cannot resolve: ~S" def-source)))))))))
674    
675    (defun gf-method-definitions (gf)
676      (mapcar #'method-definition (pcl::generic-function-methods gf)))
677    
678    (defun function-definitions (name)
679      "Return definitions for NAME in the \"function namespace\", i.e.,
680    regular functions, generic functions, methods and macros.
681    NAME can any valid function name (e.g, (setf car))."
682      (cond ((and (symbolp name) (macro-function name))
683             (list `((defmacro ,name)
684                     ,(function-location (macro-function name)))))
685            ((and (symbolp name) (special-operator-p name))
686             (list `((:special-operator ,name)
687                     (:error ,(format nil "Special operator: ~S" name)))))
688            ((and (ext:valid-function-name-p name)
689                  (ext:info :function :definition name))
690             (let ((function (coerce name 'function)))
691               (cond ((genericp function)
692                      (cons (list `(defgeneric ,name)
693                                  (function-location function))
694                            (gf-method-definitions function)))
695                     (t (list (list `(function ,name)
696                                    (function-location function)))))))))
697    
698    (defun maybe-make-definition (function kind name)
699      (if function
700          (list (list `(,kind ,name) (function-location function)))))
701    
702    (defun type-definitions (name)
703      (maybe-make-definition (ext:info :type :expander name) 'deftype name))
704    
705    (defun find-dd (name)
706      (let ((layout (ext:info :type :compiler-layout name)))
707        (if layout
708            (kernel:layout-info layout))))
709    
710    (defun struct-definitions (name)
711      (let ((dd (and (symbolp name) (find-dd name))))
712        (if dd
713            (list (list `(defstruct ,name) (dd-location dd))))))
714    
715    (defun setf-definitions (name)
716      (let ((function (or (ext:info :setf :inverse name)
717                          (ext:info :setf :expander name))))
718        (if function
719            (list (list `(setf ,name)
720                        (function-location (coerce function 'function)))))))
721    
722    (defun compiler-macro-definitions (symbol)
723      (maybe-make-definition (compiler-macro-function symbol)
724                             'define-compiler-macro
725                             symbol))
726    
727    (defun source-transform-definitions (name)
728      (maybe-make-definition (ext:info :function :source-transform name)
729                             'c:def-source-transform
730                             name))
731    
732    (defun function-info-definitions (name)
733      (let ((info (ext:info :function :info name)))
734        (if info
735            (append (loop for transform in (c::function-info-transforms info)
736                          collect (list `(c:deftransform ,name
737                                          ,(c::type-specifier
738                                            (c::transform-type transform)))
739                                        (function-location (c::transform-function
740                                                            transform))))
741                    (maybe-make-definition (c::function-info-derive-type info)
742                                           'c::derive-type name)
743                    (maybe-make-definition (c::function-info-optimizer info)
744                                           'c::optimizer name)
745                    (maybe-make-definition (c::function-info-ltn-annotate info)
746                                           'c::ltn-annotate name)
747                    (maybe-make-definition (c::function-info-ir2-convert info)
748                                           'c::ir2-convert name)
749                    (loop for template in (c::function-info-templates info)
750                          collect (list `(c::vop ,(c::template-name template))
751                                        (function-location
752                                         (c::vop-info-generator-function
753                                          template))))))))
754    
755    (defun ir1-translator-definitions (name)
756      (maybe-make-definition (ext:info :function :ir1-convert name)
757                             'c:def-ir1-translator name))
758    
759    (defimplementation find-definitions (name)
760      (append (function-definitions name)
761              (setf-definitions name)
762              (struct-definitions name)
763              (type-definitions name)
764              (compiler-macro-definitions name)
765              (source-transform-definitions name)
766              (function-info-definitions name)
767              (ir1-translator-definitions name)))
768    
769  ;;;; Documentation.  ;;;; Documentation.
770    
771  (defmethod describe-symbol-for-emacs (symbol)  (defimplementation describe-symbol-for-emacs (symbol)
772    (let ((result '()))    (let ((result '()))
773      (flet ((doc (kind)      (flet ((doc (kind)
774               (or (documentation symbol kind) :not-documented))               (or (documentation symbol kind) :not-documented))
# Line 734  The second return value is the condition Line 814  The second return value is the condition
814                         (doc nil)))                         (doc nil)))
815        result)))        result)))
816    
817  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
818    (print-description-to-string    (ecase namespace
819     (or (ext:info setf inverse (from-string symbol-name))      (:variable
820         (ext:info setf expander (from-string symbol-name)))))       (describe symbol))
821        ((:function :generic-function)
822  (defslimefun describe-type (symbol-name)       (describe (symbol-function symbol)))
823    (print-description-to-string      (:setf
824     (kernel:values-specifier-type (from-string symbol-name))))       (describe (or (ext:info setf inverse symbol))
825                   (ext:info setf expander symbol)))
826  (defslimefun describe-class (symbol-name)      (:type
827    (print-description-to-string (find-class (from-string symbol-name) nil)))       (describe (kernel:values-specifier-type symbol)))
828        (:class
829  (defslimefun describe-alien-type (symbol-name)       (describe (find-class symbol)))
830    (let ((name (from-string symbol-name)))      (:alien-type
831      (ecase (ext:info :alien-type :kind name)       (ecase (ext:info :alien-type :kind symbol)
832        (:primitive         (:primitive
833         (print-description-to-string          (describe (let ((alien::*values-type-okay* t))
834          (let ((alien::*values-type-okay* t))                      (funcall (ext:info :alien-type :translator symbol)
835            (funcall (ext:info :alien-type :translator name) (list name)))))                               (list symbol)))))
836        ((:defined)         ((:defined)
837         (print-description-to-string (ext:info :alien-type :definition name)))          (describe (ext:info :alien-type :definition symbol)))
838        (:unknown         (:unknown
839         (format nil "Unkown alien type: ~A" symbol-name)))))          (format nil "Unkown alien type: ~S" symbol))))
840        (:alien-struct
841  (defmacro %describe-alien (symbol-name namespace)       (describe (ext:info :alien-type :struct symbol)))
842    `(print-description-to-string      (:alien-union
843      (ext:info :alien-type ,namespace (from-string ,symbol-name))))       (describe (ext:info :alien-type :union symbol)))
844        (:alien-enum
845  (defslimefun describe-alien-struct (symbol-name)       (describe (ext:info :alien-type :enum symbol)))))
846    (%describe-alien symbol-name :struct))  
847    (defimplementation arglist (symbol)
848  (defslimefun describe-alien-union (symbol-name)    (let* ((fun (or (macro-function symbol)
849    (%describe-alien symbol-name :union))                    (symbol-function symbol)))
850             (arglist
851  (defslimefun describe-alien-enum (symbol-name)            (cond ((eval:interpreted-function-p fun)
852    (%describe-alien symbol-name :enum))                   (eval:interpreted-function-arglist fun))
853                    ((pcl::generic-function-p fun)
854  (defmethod arglist-string (fname)                   (pcl:generic-function-lambda-list fun))
855    "Return a string describing the argument list for FNAME.                  ((kernel:%function-arglist (kernel:%function-self fun)))
856  The result has the format \"(...)\"."                  ;; this should work both for
857    (declare (type string fname))                  ;; compiled-debug-function and for
858    (multiple-value-bind (function condition)                  ;; interpreted-debug-function
859        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))                  (t (let ((df (di::function-debug-function fun)))
860      (when condition                       (if df
861        (return-from arglist-string (format nil "(-- ~A)" condition)))                           (di::debug-function-lambda-list df)
862      (let ((arglist                           "(<arglist-unavailable>)"))))))
863             (if (not (or (fboundp function)      (check-type arglist (or list string))
864                          (functionp function)))      arglist))
                "(-- <Unknown-Function>)"  
                (let* ((fun (or (macro-function function)  
                                (symbol-function function)))  
                       (df (di::function-debug-function fun))  
                       (arglist (kernel:%function-arglist fun)))  
                  (cond ((eval:interpreted-function-p fun)  
                         (eval:interpreted-function-arglist fun))  
                        ((pcl::generic-function-p fun)  
                         (pcl::gf-pretty-arglist fun))  
                        (arglist arglist)  
                        ;; this should work both for  
                        ;; compiled-debug-function and for  
                        ;; interpreted-debug-function  
                        (df (di::debug-function-lambda-list df))  
                        (t "(<arglist-unavailable>)"))))))  
       (if (stringp arglist)  
           arglist  
           (to-string arglist)))))  
865    
866    
867  ;;;; Miscellaneous.  ;;;; Miscellaneous.
868    
869  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
870    (walker:macroexpand-all form))    (walker:macroexpand-all form))
871    
872  (defun tracedp (fname)  ;; (in-package :c)
873    (gethash (debug::trace-fdefinition fname)  ;;
874             debug::*traced-functions*))  ;; (defun swank-backend::expand-ir1-top-level (form)
875    ;;   "A scaled down version of the first pass of the compiler."
876  (defslimefun toggle-trace-fdefinition (fname-string)  ;;   (with-compilation-unit ()
877    (let ((fname (from-string fname-string)))  ;;     (let* ((*lexical-environment*
878      (cond ((tracedp fname)  ;;             (make-lexenv :default (make-null-environment)
879             (debug::untrace-1 fname)  ;;                          :cookie *default-cookie*
880             (format nil "~S is now untraced." fname))  ;;                          :interface-cookie *default-interface-cookie*))
881            (t  ;;            (*source-info* (make-lisp-source-info form))
882             (debug::trace-1 fname (debug::make-trace-info))  ;;            (*block-compile* nil)
883             (format nil "~S is now traced." fname)))))  ;;            (*block-compile-default* nil))
884    ;;       (with-ir1-namespace
885    ;;           (clear-stuff)
886    ;;         (find-source-paths form 0)
887    ;;         (ir1-top-level form '(0) t)))))
888    ;;
889    ;; (in-package :swank-backend)
890    ;;
891    ;; (defun print-ir1-converted-blocks (form)
892    ;;   (with-output-to-string (*standard-output*)
893    ;;     (c::print-all-blocks (expand-ir1-top-level (from-string form)))))
894    ;;
895    ;; (defun print-compilation-trace (form)
896    ;;   (with-output-to-string (*standard-output*)
897    ;;     (with-input-from-string (s form)
898    ;;       (ext:compile-from-stream s
899    ;;                                :verbose t
900    ;;                                :progress t
901    ;;                                :trace-stream *standard-output*))))
902    
903  (defslimefun set-default-directory (directory)  (defun set-default-directory (directory)
904    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
905    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
906    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
907    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
908    (namestring (ext:default-directory)))    (namestring (ext:default-directory)))
909    
910    ;;; source-path-{stream,file,string,etc}-position moved into
911  ;;;; Source-paths  ;;; swank-source-path-parser
   
 ;;; 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))))))  
912    
913  (defun code-location-stream-position (code-location stream)  (defun code-location-stream-position (code-location stream)
914    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the    "Return the byte offset of CODE-LOCATION in STREAM.  Extract the
# Line 995  to find the position of the correspondin Line 975  to find the position of the correspondin
975    (safe-definition-finding    (safe-definition-finding
976     (source-location-from-code-location code-location)))     (source-location-from-code-location code-location)))
977    
 (defslimefun getpid ()  
   (unix:unix-getpid))  
   
978    
979  ;;;; Debugging  ;;;; Debugging
980    
981  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
982    
983  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
984    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
985    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
986           (*sldb-restarts* (compute-restarts *swank-debugger-condition*))           (debug:*stack-top-hint* nil))
          (debug:*stack-top-hint* nil)  
          (*debugger-hook* nil)  
          (*readtable* (or debug:*debug-readtable* *readtable*))  
          (*print-level* debug:*debug-print-level*)  
          (*print-length* debug:*debug-print-length*)  
          (*print-readably* nil))  
987      (handler-bind ((di:debug-condition      (handler-bind ((di:debug-condition
988                      (lambda (condition)                      (lambda (condition)
989                        (signal (make-condition                        (signal (make-condition
# Line 1021  to find the position of the correspondin Line 991  to find the position of the correspondin
991                                 :original-condition condition)))))                                 :original-condition condition)))))
992        (funcall debugger-loop-fn))))        (funcall debugger-loop-fn))))
993    
 (defun format-restarts-for-emacs ()  
   "Return a list of restarts for *swank-debugger-condition* in a  
 format suitable for Emacs."  
   (loop for restart in *sldb-restarts*  
         collect (list (princ-to-string (restart-name restart))  
                       (princ-to-string restart))))  
   
 (defun format-condition-for-emacs ()  
   (format nil "~A~%   [Condition of type ~S]"  
           (debug::safe-condition-message *swank-debugger-condition*)  
           (type-of *swank-debugger-condition*)))  
   
994  (defun nth-frame (index)  (defun nth-frame (index)
995    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (di:frame-down frame))
996         (i index (1- i)))         (i index (1- i)))
997        ((zerop i) frame)))        ((zerop i) frame)))
998    
999  (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."  
1000    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
1001      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (di:frame-down f)
1002            for i from start below end            for i from start below end
1003            while f            while f
1004            collect f)))            collect f)))
1005    
1006  (defmethod backtrace (start end)  (defimplementation print-frame (frame stream)
1007    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (let ((*standard-output* stream))
1008        (debug::print-frame-call frame :verbosity 1 :number nil)))
 (defmethod debugger-info-for-emacs (start end)  
   (list (format-condition-for-emacs)  
         (format-restarts-for-emacs)  
         (backtrace start end)))  
1009    
1010  (defmethod frame-source-location-for-emacs (index)  (defimplementation frame-source-location-for-emacs (index)
1011    (code-location-source-location (di:frame-code-location (nth-frame index))))    (code-location-source-location (di:frame-code-location (nth-frame index))))
1012    
1013  (defmethod eval-in-frame (form index)  (defimplementation eval-in-frame (form index)
1014    (di:eval-in-frame (nth-frame index) form))    (di:eval-in-frame (nth-frame index) form))
1015    
1016  (defslimefun pprint-eval-string-in-frame (string index)  (defimplementation frame-locals (index)
   (swank-pprint  
    (multiple-value-list  
     (di:eval-in-frame (nth-frame index) (from-string string)))))  
   
 (defslimefun inspect-in-frame (string index)  
   (reset-inspector)  
   (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))  
   
 (defmethod frame-locals (index)  
1017    (let* ((frame (nth-frame index))    (let* ((frame (nth-frame index))
1018           (location (di:frame-code-location frame))           (location (di:frame-code-location frame))
1019           (debug-function (di:frame-debug-function frame))           (debug-function (di:frame-debug-function frame))
1020           (debug-variables (di::debug-function-debug-variables debug-function)))           (debug-variables (di::debug-function-debug-variables debug-function)))
1021      (loop for v across debug-variables      (loop for v across debug-variables collect
1022            collect (list            (list :name (di:debug-variable-symbol v)
1023                     :symbol (di:debug-variable-symbol v)                  :id (di:debug-variable-id v)
1024                     :id (di:debug-variable-id v)                  :value (ecase (di:debug-variable-validity v location)
1025                     :value-string                           (:valid
1026                     (if (eq (di:debug-variable-validity v location)                            (di:debug-variable-value v frame))
1027                             :valid)                           ((:invalid :unknown)
1028                         (to-string (di:debug-variable-value v frame))                            ':not-available))))))
1029                         "<not-available>")))))  
1030    (defimplementation frame-catch-tags (index)
1031  (defmethod frame-catch-tags (index)    (mapcar #'car (di:frame-catches (nth-frame index))))
1032    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  
1033          collect `(,tag . ,(code-location-source-location code-location))))  (defun set-step-breakpoints (frame)
1034      (when (di:debug-block-elsewhere-p (di:code-location-debug-block
1035  (defslimefun invoke-nth-restart (index)                                       (di:frame-code-location frame)))
1036    (invoke-restart-interactively (nth-restart index)))      (error "Cannot step, in elsewhere code~%"))
1037      (let* ((code-location (di:frame-code-location frame))
1038             (debug::*bad-code-location-types*
1039              (remove :call-site debug::*bad-code-location-types*))
1040             (next (debug::next-code-locations code-location)))
1041        (cond (next
1042               (let ((steppoints '()))
1043                 (flet ((hook (frame breakpoint)
1044                          (let ((debug:*stack-top-hint* frame))
1045                            (mapc #'di:delete-breakpoint steppoints)
1046                            (let ((cl (di::breakpoint-what breakpoint)))
1047                              (break "Breakpoint: ~S ~S"
1048                                     (di:code-location-kind cl)
1049                                     (di::compiled-code-location-pc cl))))))
1050                   (dolist (code-location next)
1051                     (let ((bp (di:make-breakpoint #'hook code-location
1052                                                   :kind :code-location)))
1053                       (di:activate-breakpoint bp)
1054                       (push bp steppoints))))))
1055             (t
1056              (flet ((hook (frame breakpoint values cookie)
1057                       (declare (ignore cookie))
1058                       (di:delete-breakpoint breakpoint)
1059                       (let ((debug:*stack-top-hint* frame))
1060                         (break "Function-end: ~A ~A" breakpoint values))))
1061                (let* ((debug-function (di:frame-debug-function frame))
1062                       (bp (di:make-breakpoint #'hook debug-function
1063                                               :kind :function-end)))
1064                  (di:activate-breakpoint bp)))))))
1065    
1066    ;; (defslimefun sldb-step (frame)
1067    ;;   (cond ((find-restart 'continue *swank-debugger-condition*)
1068    ;;          (set-step-breakpoints (nth-frame frame))
1069    ;;          (continue *swank-debugger-condition*))
1070    ;;         (t
1071    ;;          (error "Cannot continue in from condition: ~A"
1072    ;;                 *swank-debugger-condition*))))
1073    
1074    (defun frame-cfp (frame)
1075      "Return the Control-Stack-Frame-Pointer for FRAME."
1076      (etypecase frame
1077        (di::compiled-frame (di::frame-pointer frame))
1078        ((or di::interpreted-frame null) -1)))
1079    
1080    (defun frame-ip (frame)
1081      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1082      (if (not frame)
1083          -1
1084          (let ((debug-fun (di::frame-debug-function frame)))
1085            (etypecase debug-fun
1086              (di::compiled-debug-function
1087               (let* ((code-loc (di:frame-code-location frame))
1088                      (component (di::compiled-debug-function-component debug-fun))
1089                      (pc (di::compiled-code-location-pc code-loc))
1090                      (ip (sys:without-gcing
1091                           (sys:sap-int
1092                            (sys:sap+ (kernel:code-instructions component) pc)))))
1093                 (values ip pc)))
1094              ((or di::bogus-debug-function di::interpreted-debug-function)
1095               -1)))))
1096    
1097    (defun frame-registers (frame)
1098      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1099      (let* ((cfp (frame-cfp frame))
1100             (csp (frame-cfp (di::frame-up frame)))
1101             (ip (frame-ip frame))
1102             (ocfp (frame-cfp (di::frame-down frame)))
1103             (lra (frame-ip (di::frame-down frame))))
1104        (values csp cfp ip ocfp lra)))
1105    
1106    (defun print-frame-registers (frame-number)
1107      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1108        (flet ((fixnum (p) (etypecase p
1109                             (integer p)
1110                             (sys:system-area-pointer (sys:sap-int p)))))
1111          (apply #'format t "~
1112    CSP  =  ~X
1113    CFP  =  ~X
1114    IP   =  ~X
1115    OCFP =  ~X
1116    LRA  =  ~X~%" (mapcar #'fixnum
1117                          (multiple-value-list (frame-registers frame)))))))
1118    
1119    
1120    (defimplementation disassemble-frame (frame-number)
1121      "Return a string with the disassembly of frames code."
1122      (print-frame-registers frame-number)
1123      (terpri)
1124      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1125             (debug-fun (di::frame-debug-function frame)))
1126        (etypecase debug-fun
1127          (di::compiled-debug-function
1128           (let* ((component (di::compiled-debug-function-component debug-fun))
1129                  (fun (di:debug-function-function debug-fun)))
1130             (if fun
1131                 (disassemble fun)
1132                 (disassem:disassemble-code-component component))))
1133          (di::bogus-debug-function
1134           (format t "~%[Disassembling bogus frames not implemented]")))))
1135    
1136    #+(or)
1137    (defun print-binding-stack ()
1138      (flet ((bsp- (p) (sys:sap+ p (- (* vm:binding-size vm:word-bytes))))
1139             (frob (p offset) (kernel:make-lisp-obj (sys:sap-ref-32 p offset))))
1140        (do ((bsp (bsp- (kernel:binding-stack-pointer-sap)) (bsp- bsp))
1141             (start (sys:int-sap (lisp::binding-stack-start))))
1142            ((sys:sap= bsp start))
1143          (format t "~X:  ~S = ~S~%"
1144                  (sys:sap-int bsp)
1145                  (frob bsp (* vm:binding-symbol-slot vm:word-bytes))
1146                  (frob bsp (* vm:binding-value-slot vm:word-bytes))))))
1147    
1148    ;; (print-binding-stack)
1149    
1150    #+(or)
1151    (defun print-catch-blocks ()
1152      (do ((b (di::descriptor-sap lisp::*current-catch-block*)
1153              (sys:sap-ref-sap b (* vm:catch-block-previous-catch-slot
1154                                    vm:word-bytes))))
1155          (nil)
1156        (let ((int (sys:sap-int b)))
1157          (when (zerop int) (return))
1158          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1159            (let ((uwp (ref vm:catch-block-current-uwp-slot))
1160                  (cfp (ref vm:catch-block-current-cont-slot))
1161                  (tag (ref vm:catch-block-tag-slot))
1162                  )
1163          (format t "~X:  uwp = ~8X  cfp = ~8X  tag = ~X~%"
1164                  int uwp cfp (kernel:make-lisp-obj tag)))))))
1165    
1166    ;; (print-catch-blocks)
1167    
1168    #+(or)
1169    (defun print-unwind-blocks ()
1170      (do ((b (di::descriptor-sap lisp::*current-unwind-protect-block*)
1171              (sys:sap-ref-sap b (* vm:unwind-block-current-uwp-slot
1172                                    vm:word-bytes))))
1173          (nil)
1174        (let ((int (sys:sap-int b)))
1175          (when (zerop int) (return))
1176          (flet ((ref (offset) (sys:sap-ref-32 b (* offset vm:word-bytes))))
1177            (let ((cfp (ref vm:unwind-block-current-cont-slot)))
1178              (format t "~X:  cfp = ~X~%" int cfp))))))
1179    
1180  (defslimefun sldb-abort ()  ;; (print-unwind-blocks)
   (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))  
1181    
1182    
1183  ;;;; Inspecting  ;;;; Inspecting
1184    
 (defvar *inspectee*)  
 (defvar *inspectee-parts*)  
 (defvar *inspector-stack* '())  
 (defvar *inspector-history* (make-array 10 :adjustable t :fill-pointer 0))  
 (defvar *inspect-length* 30)  
   
 (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))))))  
1185  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1186    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1187      vm:function-pointer-type      vm:function-pointer-type
# Line 1168  stack." Line 1206  stack."
1206       (append (apropos-list "-TYPE" "VM" t)       (append (apropos-list "-TYPE" "VM" t)
1207               (apropos-list "-TYPE" "BIGNUM" t)))))               (apropos-list "-TYPE" "BIGNUM" t)))))
1208    
1209  (defun describe-primitive-type (object)  (defimplementation describe-primitive-type (object)
1210    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1211      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1212             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1213        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1214        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1215                                    vm:function-pointer-type                                   vm:function-pointer-type
1216                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
1217                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
1218                                    ))                                   ))
1219               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
1220                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
1221                                         :key #'symbol-value)))                                    :key #'symbol-value)))
1222                 (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."))  
1223    
1224  (defmethod inspected-parts (o)  (defimplementation inspected-parts (o)
1225    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
1226           (inspected-parts-of-value-cell o))           (inspected-parts-of-value-cell o))
1227          (t          (t
# Line 1235  nil if there's no second element." Line 1239  nil if there's no second element."
1239    (values (format nil "~A~% is a value cell." o)    (values (format nil "~A~% is a value cell." o)
1240            (list (cons "Value" (c:value-cell-ref o)))))            (list (cons "Value" (c:value-cell-ref o)))))
1241    
 ;; 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.~%")))))))  
   
1242  (defmethod inspected-parts ((o function))  (defmethod inspected-parts ((o function))
1243    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
1244      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
# Line 1304  nil if there's no second element." Line 1275  nil if there's no second element."
1275            `(("Name" . ,(kernel:fdefn-name o))            `(("Name" . ,(kernel:fdefn-name o))
1276              ("Function" . ,(kernel:fdefn-function o)))))              ("Function" . ,(kernel:fdefn-function o)))))
1277    
1278  ;;; Local Variables:  
1279  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))  ;;;; Profiling
1280  ;;; End:  (defimplementation profile (fname)
1281      (eval `(profile:profile ,fname)))
1282    
1283    (defimplementation unprofile (fname)
1284      (eval `(profile:unprofile ,fname)))
1285    
1286    (defimplementation unprofile-all ()
1287      (eval '(profile:unprofile))
1288      "All functions unprofiled.")
1289    
1290    (defimplementation profile-report ()
1291      (eval '(profile:report-time)))
1292    
1293    (defimplementation profile-reset ()
1294      (eval '(profile:reset-time))
1295      "Reset profiling counters.")
1296    
1297    (defimplementation profiled-functions ()
1298      profile:*timed-functions*)
1299    
1300    (defimplementation profile-package (package callers methods)
1301      (profile:profile-all :package package
1302                           :callers-p callers
1303                           :methods methods))
1304    
1305    
1306    ;;;; Multiprocessing
1307    
1308    #+MP
1309    (progn
1310      (defimplementation startup-multiprocessing ()
1311        ;; Threads magic: this never returns! But top-level becomes
1312        ;; available again.
1313        (mp::startup-idle-and-top-level-loops))
1314    
1315      (defimplementation spawn (fn &key (name "Anonymous"))
1316        (mp:make-process fn :name name))
1317    
1318      (defimplementation thread-name (thread)
1319        (mp:process-name thread))
1320    
1321      (defimplementation thread-status (thread)
1322        (mp:process-whostate thread))
1323    
1324      (defimplementation current-thread ()
1325        mp:*current-process*)
1326    
1327      (defimplementation all-threads ()
1328        (copy-list mp:*all-processes*))
1329    
1330      (defimplementation interrupt-thread (thread fn)
1331        (mp:process-interrupt thread fn))
1332    
1333      (defimplementation kill-thread (thread)
1334        (mp:destroy-process thread))
1335    
1336      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
1337    
1338      (defstruct (mailbox (:conc-name mailbox.))
1339        (mutex (mp:make-lock "process mailbox"))
1340        (queue '() :type list))
1341    
1342      (defun mailbox (thread)
1343        "Return THREAD's mailbox."
1344        (mp:with-lock-held (*mailbox-lock*)
1345          (or (getf (mp:process-property-list thread) 'mailbox)
1346              (setf (getf (mp:process-property-list thread) 'mailbox)
1347                    (make-mailbox)))))
1348    
1349      (defimplementation send (thread message)
1350        (let* ((mbox (mailbox thread))
1351               (mutex (mailbox.mutex mbox)))
1352          (mp:with-lock-held (mutex)
1353            (setf (mailbox.queue mbox)
1354                  (nconc (mailbox.queue mbox) (list message))))))
1355    
1356      (defimplementation receive ()
1357        (let* ((mbox (mailbox mp:*current-process*))
1358               (mutex (mailbox.mutex mbox)))
1359          (mp:process-wait "receive" #'mailbox.queue mbox)
1360          (mp:with-lock-held (mutex)
1361            (pop (mailbox.queue mbox)))))
1362    
1363      )

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

  ViewVC Help
Powered by ViewVC 1.1.5