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.112 by heller, Fri Jul 30 21:39:15 2004 UTC
# Line 1  Line 1 
1  ;;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-  ;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
2    ;;;
3    ;;; License: Public Domain
4    ;;;
5    ;;;; Introduction
6    ;;;
7    ;;; This is the CMUCL implementation of the `swank-backend' package.
9    (in-package :swank-backend)
11  (declaim (optimize debug))  ;;;; "Hot fixes"
12    ;;;
13    ;;; Here are necessary bugfixes to the latest released version of
14    ;;; CMUCL (currently 18e). Any fixes placed here should also be
15    ;;; submitted to the `cmucl-imp' mailing list and confirmed as
16    ;;; good. When a new release is made that includes the fixes we should
17    ;;; promptly delete them from here. It is enough to be compatible with
18    ;;; the latest release.
20    (in-package :lisp)
22  (in-package :swank)  ;;; `READ-SEQUENCE' with large sequences has problems in 18e. This new
23    ;;; definition works better.
25  ;; Turn on xref. [should we?]  #+cmu18e
26  (setf c:*record-xref-info* t)  (progn
27      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
28        (when s
29          (setf (symbol-value s) nil)))
31      (defun read-into-simple-string (s stream start end)
32        (declare (type simple-string s))
33        (declare (type stream stream))
34        (declare (type index start end))
35        (unless (subtypep (stream-element-type stream) 'character)
36          (error 'type-error
37                 :datum (read-char stream nil #\Null)
38                 :expected-type (stream-element-type stream)
39                 :format-control "Trying to read characters from a binary stream."))
40        ;; Let's go as low level as it seems reasonable.
41        (let* ((numbytes (- end start))
42               (total-bytes 0))
43          ;; read-n-bytes may return fewer bytes than requested, so we need
44          ;; to keep trying.
45          (loop while (plusp numbytes) do
46                (let ((bytes-read (system:read-n-bytes stream s start numbytes nil)))
47                  (when (zerop bytes-read)
48                    (return-from read-into-simple-string total-bytes))
49                  (incf total-bytes bytes-read)
50                  (incf start bytes-read)
51                  (decf numbytes bytes-read)))
52          total-bytes))
54      (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
55        (when s
56          (setf (symbol-value s) t)))
58  (defun without-interrupts* (body)    )
   (sys:without-interrupts (funcall body)))  
60  (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)))))  
63  ;;;; TCP server.  ;;;; TCP server
64    ;;;
65    ;;; In CMUCL we support all communication styles. By default we use
66    ;;; `:SIGIO' because it is the most responsive, but it's somewhat
67    ;;; dangerous: CMUCL is not in general "signal safe", and you don't
68    ;;; know for sure what you'll be interrupting. Both `:FD-HANDLER' and
69    ;;; `:SPAWN' are reasonable alternatives.
71    (defimplementation preferred-communication-style ()
72      :sigio)
74    (defimplementation create-socket (host port)
75      (ext:create-inet-listener port :stream
76                                :reuse-address t
77                                :host (resolve-hostname host)))
79    (defimplementation local-port (socket)
80      (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
82    (defimplementation close-socket (socket)
83      (sys:invalidate-descriptor socket)
84      (ext:close-socket (socket-fd socket)))
86  (defun resolve-hostname (name)  (defimplementation accept-connection (socket)
87    (let* ((hostent (ext:lookup-host-entry name))    (make-socket-io-stream (ext:accept-tcp-connection socket)))
89    ;;;;; Sockets
91    (defun socket-fd (socket)
92      "Return the filedescriptor for the socket represented by SOCKET."
93      (etypecase socket
94        (fixnum socket)
95        (sys:fd-stream (sys:fd-stream-fd socket))))
97    (defun resolve-hostname (hostname)
98      "Return the IP address of HOSTNAME as an integer."
99      (let* ((hostent (ext:lookup-host-entry hostname))
100           (address (car (ext:host-entry-addr-list hostent))))           (address (car (ext:host-entry-addr-list hostent))))
101      (ext:htonl address)))      (ext:htonl address)))
103  (defun create-swank-server (port &key (reuse-address t)  (defun make-socket-io-stream (fd)
104                              (address "localhost"))    "Create a new input/output fd-stream for FD."
105    "Create a SWANK TCP server."    (sys:make-fd-stream fd :input t :output t :element-type 'base-char))
106    (let* ((ip (resolve-hostname address))  
107           (fd (ext:create-inet-listener port :stream  ;;;;; Signal-driven I/O
108                                         :reuse-address reuse-address  
109                                         :host ip)))  (defvar *sigio-handlers* '()
110      (system:add-fd-handler fd :input #'accept-connection)    "List of (key . function) pairs.
111      (nth-value 1 (ext::get-socket-host-and-port fd))))  All functions are called on SIGIO, and the key is used for removing
112    specific functions.")
113  (defun accept-connection (socket)  
114    "Accept one Swank TCP connection on SOCKET and then close it."  (defun set-sigio-handler ()
115    (setup-request-handler (ext:accept-tcp-connection socket))    (sys:enable-interrupt :sigio (lambda (signal code scp)
116    (sys:invalidate-descriptor socket)                                   (sigio-handler signal code scp))))
117    (unix:unix-close socket))  
118    (defun sigio-handler (signal code scp)
119      (declare (ignore signal code scp))
120      (mapc #'funcall (mapcar #'cdr *sigio-handlers*)))
122    (defun fcntl (fd command arg)
123      "fcntl(2) - manipulate a file descriptor."
124      (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
125        (unless ok (error "fcntl: ~A" (unix:get-unix-error-msg error)))))
127    (defimplementation add-sigio-handler (socket fn)
128      (set-sigio-handler)
129      (let ((fd (socket-fd socket)))
130        (fcntl fd unix:f-setown (unix:unix-getpid))
131        (fcntl fd unix:f-setfl unix:fasync)
132        (push (cons fd fn) *sigio-handlers*)))
134    (defimplementation remove-sigio-handlers (socket)
135      (let ((fd (socket-fd socket)))
136        (setf *sigio-handlers* (remove fd *sigio-handlers* :key #'car))
137        (sys:invalidate-descriptor fd))
138      (close socket))
140    ;;;;; SERVE-EVENT
142    (defimplementation add-fd-handler (socket fn)
143      (let ((fd (socket-fd socket)))
144        (sys:add-fd-handler fd :input (lambda (_)
145                                        _
146                                        (funcall fn)))))
148  (defun open-stream-to-emacs ()  (defimplementation remove-fd-handlers (socket)
149    "Return an output-stream to Emacs' output buffer."    (sys:invalidate-descriptor (socket-fd socket)))
   (let* ((ip (resolve-hostname "localhost"))  
          (listener (ext:create-inet-listener 0 :stream :host ip))  
          (port (nth-value 1 (ext::get-socket-host-and-port listener))))  
            (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))  
          (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*)))))  
152  ;;;; Stream handling  ;;;; Stream handling
153    ;;; XXX: How come we don't use Gray streams in CMUCL too? -luke (15/May/2004)
155    (defimplementation make-fn-streams (input-fn output-fn)
156      (let* ((output (make-slime-output-stream output-fn))
157             (input  (make-slime-input-stream input-fn output)))
158        (values input output)))
160  (defstruct (slime-output-stream  (defstruct (slime-output-stream
161               (:include lisp::lisp-stream               (:include lisp::lisp-stream
162                         (lisp::misc #'sos/misc)                         (lisp::misc #'sos/misc)
163                         (lisp::out #'sos/out)                         (lisp::out #'sos/out)
164                         (lisp::sout #'sos/sout))                         (lisp::sout #'sos/sout))
165               (:conc-name sos.)               (:conc-name sos.)
166               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
167                 (:constructor make-slime-output-stream (output-fn)))
168      (output-fn nil :type function)
169    (buffer (make-string 512) :type string)    (buffer (make-string 512) :type string)
170    (index 0 :type kernel:index)    (index 0 :type kernel:index)
171    (column 0 :type kernel:index))    (column 0 :type kernel:index))
# Line 117  The request is read from the socket as a Line 189  The request is read from the socket as a
189  (defun sos/sout (stream string start end)  (defun sos/sout (stream string start end)
190    (loop for i from start below end    (loop for i from start below end
191          do (sos/out stream (aref string i))))          do (sos/out stream (aref string i))))
193  (defun sos/misc (stream operation &optional arg1 arg2)  (defun sos/misc (stream operation &optional arg1 arg2)
194    (declare (ignore arg1 arg2))    (declare (ignore arg1 arg2))
195    (case operation    (case operation
196      ((:force-output :finish-output)      ((:force-output :finish-output)
197       (let ((end (sos.index stream)))       (let ((end (sos.index stream)))
198         (unless (zerop end)         (unless (zerop end)
199           (send-to-emacs `(:read-output ,(subseq (sos.buffer stream) 0 end)))           (funcall (sos.output-fn stream) (subseq (sos.buffer stream) 0 end))
200           (setf (sos.index stream) 0))))           (setf (sos.index stream) 0))))
201      (:charpos (sos.column stream))      (:charpos (sos.column stream))
202      (:line-length 75)      (:line-length 75)
203      (:file-position nil)      (:file-position nil)
# Line 135  The request is read from the socket as a Line 207  The request is read from the socket as a
207      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))      (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
209  (defstruct (slime-input-stream  (defstruct (slime-input-stream
210               (:include string-stream               (:include string-stream
211                         (lisp::in #'sis/in)                         (lisp::in #'sis/in)
212                         (lisp::misc #'sis/misc))                         (lisp::misc #'sis/misc))
213               (:conc-name sis.)               (:conc-name sis.)
214               (:print-function %print-slime-output-stream))               (:print-function %print-slime-output-stream)
215    (buffer "" :type string)               (:constructor make-slime-input-stream (input-fn sos)))
216    (index 0 :type kernel:index))    (input-fn nil :type function)
217      ;; We know our sibling output stream, so that we can force it before
218      ;; requesting input.
219      (sos      nil :type slime-output-stream)
220      (buffer   ""  :type string)
221      (index    0   :type kernel:index))
223  (defun sis/in (stream eof-errorp eof-value)  (defun sis/in (stream eof-errorp eof-value)
224    (declare (ignore eof-errorp eof-value))    (declare (ignore eof-errorp eof-value))
225    (let ((index (sis.index stream))    (let ((index (sis.index stream))
226          (buffer (sis.buffer stream)))          (buffer (sis.buffer stream)))
227      (when (= index (length buffer))      (when (= index (length buffer))
228        (setf buffer (slime-read-string))        (force-output (sis.sos stream))
229          (setf buffer (funcall (sis.input-fn stream)))
230        (setf (sis.buffer stream) buffer)        (setf (sis.buffer stream) buffer)
231        (setf index 0))        (setf index 0))
232      (prog1 (aref buffer index)      (prog1 (aref buffer index)
# Line 162  The request is read from the socket as a Line 240  The request is read from the socket as a
240      (:unread (setf (aref (sis.buffer stream)      (:unread (setf (aref (sis.buffer stream)
241                           (decf (sis.index stream)))                           (decf (sis.index stream)))
242                     arg1))                     arg1))
243      (:clear-input (setf (sis.index stream) 0      (:clear-input
244         (setf (sis.index stream) 0
245                          (sis.buffer stream) ""))                          (sis.buffer stream) ""))
246      (:listen (< (sis.index stream) (length (sis.buffer stream))))      (:listen (< (sis.index stream) (length (sis.buffer stream))))
247      (:charpos nil)      (:charpos nil)
# Line 174  The request is read from the socket as a Line 253  The request is read from the socket as a
254  ;;;; Compilation Commands  ;;;; Compilation Commands
 (defvar *swank-source-info* nil  
   "Bound to a SOURCE-INFO object during compilation.")  
256  (defvar *previous-compiler-condition* nil  (defvar *previous-compiler-condition* nil
257    "Used to detect duplicates.")    "Used to detect duplicates.")
259  (defvar *previous-context* nil  (defvar *previous-context* nil
260    "Previous compiler error context.")    "Previous compiler error context.")
262  (defvar *compiler-notes* '()  (defvar *buffer-name* nil
263    "List of compiler notes for the last compilation unit.")    "The name of the Emacs buffer we are compiling from.
264    NIL if we aren't compiling from a buffer.")
 (defvar *buffer-name* nil)  
266  (defvar *buffer-start-position* nil)  (defvar *buffer-start-position* nil)
267  (defvar *buffer-substring* nil)  (defvar *buffer-substring* nil)
268  (defvar *compile-filename* nil)  
269    (defimplementation call-with-compilation-hooks (function)
270      (let ((*previous-compiler-condition* nil)
271            (*previous-context* nil)
272            (*print-readably* nil))
273        (handler-bind ((c::compiler-error #'handle-notification-condition)
274                       (c::style-warning  #'handle-notification-condition)
275                       (c::warning        #'handle-notification-condition))
276          (funcall function))))
278    (defimplementation swank-compile-file (filename load-p)
279      (clear-xref-info filename)
280      (with-compilation-hooks ()
281        (let ((*buffer-name* nil))
282          (multiple-value-bind (output-file warnings-p failure-p)
283              (compile-file filename :load load-p)
284            (unless failure-p
285              ;; Cache the latest source file for definition-finding.
286              (source-cache-get filename (file-write-date filename)))
287            (values output-file warnings-p failure-p)))))
289    (defimplementation swank-compile-string (string &key buffer position)
290      (with-compilation-hooks ()
291        (let ((*buffer-name* buffer)
292              (*buffer-start-position* position)
293              (*buffer-substring* string))
294          (with-input-from-string (stream string)
295            (ext:compile-from-stream
296             stream
297             :source-info `(:emacs-buffer ,buffer
298                            :emacs-buffer-offset ,position
299                            :emacs-buffer-string ,string))))))
302  ;;;;; Trapping notes  ;;;;; Trapping notes
303    ;;;
304    ;;; We intercept conditions from the compiler and resignal them as
307  (defun handle-notification-condition (condition)  (defun handle-notification-condition (condition)
308    "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  
309    (unless (eq condition *previous-compiler-condition*)    (unless (eq condition *previous-compiler-condition*)
310      (let ((context (or (c::find-error-context nil) *previous-context*)))      (let ((context (c::find-error-context nil)))
311        (setq *previous-compiler-condition* condition)        (setq *previous-compiler-condition* condition)
312        (setq *previous-context* context)        (setq *previous-context* context)
313        (signal-compiler-condition condition context))))        (signal-compiler-condition condition context))))
# Line 211  information." Line 317  information."
317             'compiler-condition             'compiler-condition
318             :original-condition condition             :original-condition condition
319             :severity (severity-for-emacs condition)             :severity (severity-for-emacs condition)
320             :message (brief-compiler-message-for-emacs condition context)             :short-message (brief-compiler-message-for-emacs condition)
321               :message (long-compiler-message-for-emacs condition context)
322             :location (compiler-note-location context))))             :location (compiler-note-location context))))
324  (defun severity-for-emacs (condition)  (defun severity-for-emacs (condition)
# Line 221  information." Line 328  information."
328      (c::style-warning :note)      (c::style-warning :note)
329      (c::warning :warning)))      (c::warning :warning)))
331  (defun brief-compiler-message-for-emacs (condition error-context)  (defun brief-compiler-message-for-emacs (condition)
332    "Briefly describe a compiler error for Emacs.    "Briefly describe a compiler error for Emacs.
333  When Emacs presents the message it already has the source popped up  When Emacs presents the message it already has the source popped up
334  and the source form highlighted. This makes much of the information in  and the source form highlighted. This makes much of the information in
335  the error-context redundant."  the error-context redundant."
336      (princ-to-string condition))
338    (defun long-compiler-message-for-emacs (condition error-context)
339      "Describe a compiler error for Emacs including context information."
340    (declare (type (or c::compiler-error-context null) error-context))    (declare (type (or c::compiler-error-context null) error-context))
341    (multiple-value-bind (enclosing source)    (multiple-value-bind (enclosing source)
342        (if error-context        (if error-context
# Line 234  the error-context redundant." Line 345  the error-context redundant."
345      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"      (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~^~%~}~]~A"
346              enclosing source condition)))              enclosing source condition)))
348  (defun compiler-note-location (context)  (defun compiler-note-location (context)
349    (cond (context    "Derive the location of a complier message from its context.
350           (resolve-note-location  Return a `location' record, or (:error REASON) on failure."
351            *buffer-name*    (if (null context)
352            (c::compiler-error-context-file-name context)        (note-error-location)
353            (c::compiler-error-context-file-position context)        (let ((file (c::compiler-error-context-file-name context))
354            (reverse (c::compiler-error-context-original-source-path context))              (source (c::compiler-error-context-original-source context))
355            (c::compiler-error-context-original-source context)))              (path
356          (t               (reverse (c::compiler-error-context-original-source-path context))))
357           (resolve-note-location *buffer-name* nil nil nil nil))))          (or (locate-compiler-note file source path)
358                (note-error-location)))))
359  (defgeneric resolve-note-location (buffer file-name file-position  
360                                            source-path source))  (defun note-error-location ()
361      "Pseudo-location for notes that can't be located."
362  (defmethod resolve-note-location ((b (eql nil)) (f pathname) pos path source)    (list :error "No error location available."))
363    (make-location  
364     `(:file ,(unix-truename f))  (defun locate-compiler-note (file source source-path)
365     `(:position ,(1+ (source-path-file-position path f)))))    (cond ((and (eq file :stream) *buffer-name*)
366             ;; Compiling from a buffer
367  (defmethod resolve-note-location ((b string) (f (eql :stream)) pos path source)           (let ((position (+ *buffer-start-position*
368    (make-location                              (source-path-string-position
369     `(:buffer ,b)                               source-path *buffer-substring*))))
370     `(:position ,(+ *buffer-start-position*             (make-location (list :buffer *buffer-name*)
371                     (source-path-string-position path *buffer-substring*)))))                            (list :position position))))
372            ((and (pathnamep file) (null *buffer-name*))
373  (defmethod resolve-note-location (b (f (eql :lisp)) pos path (source string))           ;; Compiling from a file
374    (make-location           (make-location (list :file (unix-truename file))
375     `(:source-form ,source)                          (list :position
376     `(:position 1)))                                (1+ (source-path-file-position
377                                       source-path file)))))
378  (defmethod resolve-note-location (buffer          ((and (eq file :lisp) (stringp source))
379                                    (file (eql nil))           ;; No location known, but we have the source form.
380                                    (pos (eql nil))           ;; XXX How is this case triggered?  -luke (16/May/2004)
381                                    (path (eql nil))           ;; This can happen if the compiler needs to expand a macro
382                                    (source (eql nil)))           ;; but the macro-expander is not yet compiled.  Calling the
383    (cond (buffer           ;; (interpreted) macro-expander triggers IR1 conversion of
384           (make-location (list :buffer buffer)           ;; the lambda expression for the expander and invokes the
385                          (list :position *buffer-start-position*)))           ;; compiler recursively.
386          (*compile-file-truename*           (make-location (list :source-form source)
387           (make-location (list :file (namestring *compile-file-truename*))                          (list :position 1)))))
                         (list :position 0)))  
          (make-location (list :file *compile-filename*) (list :position 0)))  
          (list :error "No error location available"))))  
 (defmacro with-compilation-hooks (() &body body)  
   "Execute BODY and record the set of compiler notes."  
   `(let ((*previous-compiler-condition* nil)  
          (*previous-context* nil)  
          (*print-readably* nil))  
     (handler-bind ((c::compiler-error #'handle-notification-condition)  
                    (c::style-warning  #'handle-notification-condition)  
                    (c::warning        #'handle-notification-condition))  
 (defmethod compile-file-for-emacs (filename load-p)  
   (clear-xref-info filename)  
   (with-compilation-hooks ()  
     (let ((*buffer-name* nil)  
           (*compile-filename* filename))  
         (compile-file filename :load load-p))))  
389  (defmethod compile-string-for-emacs (string &key buffer position)  (defun unix-truename (pathname)
390    (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)  
          :source-info `(:emacs-buffer ,buffer  
                         :emacs-buffer-offset ,position  
                         :emacs-buffer-string ,string))))))  
393  ;;;; XREF  ;;;; XREF
394    ;;;
395    ;;; Cross-reference support is based on the standard CMUCL `XREF'
396    ;;; package. This package has some caveats: XREF information is
397    ;;; recorded during compilation and not preserved in fasl files, and
398    ;;; XREF recording is disabled by default. Redefining functions can
399    ;;; also cause duplicate references to accumulate, but
400    ;;; `swank-compile-file' will automatically clear out any old records
401    ;;; from the same filename.
402    ;;;
403    ;;; To enable XREF recording, set `c:*record-xref-info*' to true. To
404    ;;; clear out the XREF database call `xref:init-xref-database'.
406  (defun lookup-xrefs (finder name)  (defmacro defxref (name function)
407    (xref-results-for-emacs (funcall finder (from-string name))))    `(defimplementation ,name (name)
408        (xref-results (,function name))))
409  (defslimefun who-calls (function-name)  
410    "Return the places where FUNCTION-NAME is called."  (defxref who-calls      xref:who-calls)
411    (lookup-xrefs #'xref:who-calls function-name))  (defxref who-references xref:who-references)
412    (defxref who-binds      xref:who-binds)
413  (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))  
415    ;;; More types of XREF information were added since 18e:
416    ;;;
417  #+cmu19  #+cmu19
418  (progn  (progn
419    (defslimefun who-macroexpands (macro)    (defxref who-macroexpands xref:who-macroexpands)
420      "Return the places where MACRO is expanded."    ;; XXX
421      (lookup-xrefs #'xref:who-macroexpands macro))    (defimplementation who-specializes (symbol)
422        (let* ((methods (xref::who-specializes (find-class symbol)))
423    (defslimefun who-specializes (class)             (locations (mapcar #'method-location methods)))
424      "Return the methods with specializers for CLASS."        (mapcar #'list methods locations))))
425      (let* ((methods (xref::who-specializes (find-class (from-string class))))  
426             (locations (mapcar #'method-source-location methods)))  (defun xref-results (contexts)
427        (group-xrefs (mapcar (lambda (m l)    (mapcar (lambda (xref)
428                               (cons (let ((*print-pretty* nil))              (list (xref:xref-context-name xref)
429                                       (to-string m))                    (resolve-xref-location xref)))
430                                     l))            contexts))
                            methods locations))))  
432  (defun resolve-xref-location (xref)  (defun resolve-xref-location (xref)
433    (let ((name (xref:xref-context-name xref))    (let ((name (xref:xref-context-name xref))
# Line 363  the error-context redundant." Line 441  the error-context redundant."
441             (make-location (list :file (unix-truename file))             (make-location (list :file (unix-truename file))
442                            (list :function-name (string name))))                            (list :function-name (string name))))
443            (t            (t
444             `(:error ,(format nil "Unkown source location: ~S ~S ~S "             `(:error ,(format nil "Unknown source location: ~S ~S ~S "
445                               name file source-path))))))                               name file source-path))))))
 (defun xref-results-for-emacs (contexts)  
   "Prepare a list of xref contexts for Emacs.  
 The result is a list of xrefs:  
 group       ::= (FILENAME . ({reference}+))  
   (let ((xrefs '()))  
     (dolist (cxt contexts)  
       (let ((name (xref:xref-context-name cxt)))  
         (push (cons (to-string name)  
                     (resolve-xref-location cxt))  
     (group-xrefs xrefs)))  
 (defun location-buffer= (location1 location2)  
   (equalp location1 location2))  
 (defun file-xrefs-for-emacs (unix-filename contexts)  
   "Return a summary of the references from a particular file.  
 The result is a list of the form (FILENAME ((REFERRER SOURCE-PATH) ...))"  
   (list unix-filename  
         (loop for context in (sort-contexts-by-source-path contexts)  
               collect (list (let ((*print-pretty* nil))  
                               (to-string (xref:xref-context-name context)))  
                             (xref:xref-context-source-path context)))))  
 (defun sort-contexts-by-source-path (contexts)  
   "Sort xref contexts by lexical position of source-paths.  
 It is assumed that all contexts belong to the same file."  
   (sort contexts #'source-path< :key #'xref:xref-context-source-path))  
 (defun source-path< (path1 path2)  
   "Return true if PATH1 is lexically before PATH2."  
   (and (every #'< path1 path2)  
        (< (length path1) (length path2))))  
447  (defun clear-xref-info (namestring)  (defun clear-xref-info (namestring)
448    "Clear XREF notes pertaining to FILENAME.    "Clear XREF notes pertaining to NAMESTRING.
449  This is a workaround for a CMUCL bug: XREF records are cumulative."  This is a workaround for a CMUCL bug: XREF records are cumulative."
450    (let ((filename (parse-namestring namestring)))    (when c:*record-xref-info*
451      (when c:*record-xref-info*      (let ((filename (truename namestring)))
452        (dolist (db (list xref::*who-calls*        (dolist (db (list xref::*who-calls*
453                          #+cmu19 xref::*who-is-called*                          #+cmu19 xref::*who-is-called*
454                          #+cmu19 xref::*who-macroexpands*                          #+cmu19 xref::*who-macroexpands*
# Line 415  This is a workaround for a CMUCL bug: XR Line 456  This is a workaround for a CMUCL bug: XR
456                          xref::*who-binds*                          xref::*who-binds*
457                          xref::*who-sets*))                          xref::*who-sets*))
458          (maphash (lambda (target contexts)          (maphash (lambda (target contexts)
459                       ;; XXX update during traversal?
460                     (setf (gethash target db)                     (setf (gethash target db)
461                           (delete-if                           (delete filename contexts
462                            (lambda (ctx)                                   :key #'xref:xref-context-file
463                              (xref-context-derived-from-p ctx filename))                                   :test #'equalp)))
464                   db)))))                   db)))))
 (defun xref-context-derived-from-p (context filename)  
   (let ((xref-file (xref:xref-context-file context)))  
     (and xref-file (pathname= filename xref-file))))  
 (defun pathname= (&rest pathnames)  
   "True if PATHNAMES refer to the same file."  
   (apply #'string= (mapcar #'unix-truename pathnames)))  
 (defun unix-truename (pathname)  
   (ext:unix-namestring (truename pathname)))  
467  ;;;; Find callers and callees  ;;;; Find callers and callees
468    ;;;
469  ;;; Find callers and callees by looking at the constant pool of  ;;; Find callers and callees by looking at the constant pool of
470  ;;; compiled code objects.  We assume every fdefn object in the  ;;; compiled code objects.  We assume every fdefn object in the
471  ;;; constant pool corresponds to a call to that function.  A better  ;;; constant pool corresponds to a call to that function.  A better
# Line 495  constant pool." Line 525  constant pool."
525    "Return FUNCTION's callers.  The result is a list of code-objects."    "Return FUNCTION's callers.  The result is a list of code-objects."
526    (let ((referrers '()))    (let ((referrers '()))
527      (declare (inline map-caller-code-components))      (declare (inline map-caller-code-components))
528      (ext:gc :full t)      ;;(ext:gc :full t)
529      (map-caller-code-components function spaces      (map-caller-code-components function spaces
530                                  (lambda (code) (push code referrers)))                                  (lambda (code) (push code referrers)))
531      referrers))      referrers))
533  (defun debug-info-definitions (debug-info)  (defun debug-info-definitions (debug-info)
534    "Return the defintions for a debug-info.  This should only be used    "Return the defintions for a debug-info.  This should only be used
535  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 542  code (are theree others?)"
542      (destructuring-bind (first) source      (destructuring-bind (first) source
543        (ecase (c::debug-source-from first)        (ecase (c::debug-source-from first)
544          (:file          (:file
545           (list           (list (list name
546            (cons name                       (make-location
547                  (make-location                        (list :file (unix-truename (c::debug-source-name first)))
548                   (list :file (unix-truename (c::debug-source-name first)))                        (list :function-name name)))))))))
                  (list :function-name name)))))))))  
550  (defun code-component-entry-points (code)  (defun code-component-entry-points (code)
551    "Return a list ((NAME . LOCATION) ...) of function definitons for    "Return a list ((NAME LOCATION) ...) of function definitons for
552  the code omponent CODE."  the code omponent CODE."
553    (delete-duplicates    (delete-duplicates
554     (loop for e = (kernel:%code-entry-points code)     (loop for e = (kernel:%code-entry-points code)
555           then (kernel::%function-next e)           then (kernel::%function-next e)
556           while e           while e
557           collect (cons (to-string (kernel:%function-name e))           collect (list (kernel:%function-name e)
558                         (function-source-location e)))                         (function-location e)))
559     :test #'equal))     :test #'equal))
561  (defslimefun list-callers (symbol-name)  (defimplementation list-callers (symbol)
562    "Return a list ((FILE . ((NAME . LOCATION) ...)) ...) of callers."    "Return a list ((NAME LOCATION) ...) of callers."
563    (let ((components (function-callers (from-string symbol-name)))    (let ((components (function-callers symbol))
564          (xrefs '()))          (xrefs '()))
565      (dolist (code components)      (dolist (code components)
566        (let* ((entry (kernel:%code-entry-points code))        (let* ((entry (kernel:%code-entry-points code))
# Line 541  the code omponent CODE." Line 570  the code omponent CODE."
570                         (debug-info-definitions                         (debug-info-definitions
571                          (kernel:%code-debug-info code)))))                          (kernel:%code-debug-info code)))))
572          (setq xrefs (nconc defs xrefs))))          (setq xrefs (nconc defs xrefs))))
573      (group-xrefs xrefs)))      xrefs))
575    (defimplementation list-callees (symbol)
576      (let ((fns (function-callees symbol)))
577        (mapcar (lambda (fn)
578                  (list (kernel:%function-name fn)
579                        (function-location fn)))
580                fns)))
582  (defslimefun list-callees (symbol-name)  
583    (let ((fns (function-callees (from-string symbol-name))))  ;;;; Resolving source locations
584      (group-xrefs (mapcar (lambda (fn)  ;;;
585                             (cons (to-string (kernel:%function-name fn))  ;;; Our mission here is to "resolve" references to code locations into
586                                   (function-source-location fn)))  ;;; actual file/buffer names and character positions. The references
587                           fns))))  ;;; we work from come out of the compiler's statically-generated debug
588    ;;; information, such as `code-location''s and `debug-source''s. For
589  ;;;; Definitions  ;;; more details, see the "Debugger Programmer's Interface" section of
590    ;;; the CMUCL manual.
591    ;;;
592    ;;; The first step is usually to find the corresponding "source-path"
593    ;;; for the location. Once we have the source-path we can pull up the
594    ;;; source file and `READ' our way through to the right position. The
595    ;;; main source-code groveling work is done in
596    ;;; `swank-source-path-parser.lisp'.
598  (defvar *debug-definition-finding* t  (defvar *debug-definition-finding* nil
599    "When true don't handle errors while looking for definitions.    "When true don't handle errors while looking for definitions.
600  This is useful when debugging the definition-finding code.")  This is useful when debugging the definition-finding code.")
602    (defvar *source-snippet-size* 256
603      "Maximum number of characters in a snippet of source code.
604    Snippets at the beginning of definitions are used to tell Emacs what
605    the definitions looks like, so that it can accurately find them by
606    text search.")
608  (defmacro safe-definition-finding (&body body)  (defmacro safe-definition-finding (&body body)
609    "Execute BODY ignoring errors.  Return a the source location    "Execute BODY and return the source-location it returns.
610  returned by BODY or if an error occurs a description of the error.  If an error occurs and `*debug-definition-finding*' is false, then
611  The second return value is the condition or nil."  return an error pseudo-location.
613    The second return value is NIL if no error occurs, otherwise it is the
614    condition object."
615    `(flet ((body () ,@body))    `(flet ((body () ,@body))
616      (if *debug-definition-finding*      (if *debug-definition-finding*
617          (body)          (body)
618          (handler-case (values (progn ,@body) nil)          (handler-case (values (progn ,@body) nil)
619            (error (c) (values (list :error (princ-to-string c)) c))))))            (error (c) (values (list :error (princ-to-string c)) c))))))
621    (defun code-location-source-location (code-location)
622      "Safe wrapper around `code-location-from-source-location'."
623      (safe-definition-finding
624       (source-location-from-code-location code-location)))
626    (defun source-location-from-code-location (code-location)
627      "Return the source location for CODE-LOCATION."
628      (let ((debug-fun (di:code-location-debug-function code-location)))
629        (when (di::bogus-debug-function-p debug-fun)
630          ;; Those lousy cheapskates! They've put in a bogus debug source
631          ;; because the code was compiled at a low debug setting.
632          (error "Bogus debug function: ~A" debug-fun)))
633      (let* ((debug-source (di:code-location-debug-source code-location))
634             (from (di:debug-source-from debug-source))
635             (name (di:debug-source-name debug-source)))
636        (ecase from
637          (:file
638           (location-in-file name code-location debug-source))
639          (:stream
640           (location-in-stream code-location debug-source))
641          (:lisp
642           ;; The location comes from a form passed to `compile'.
643           ;; The best we can do is return the form itself for printing.
644           (make-location
645            (list :source-form (with-output-to-string (*standard-output*)
646                                 (debug::print-code-location-source-form
647                                  code-location 100 t)))
648            (list :position 1))))))
650    (defun location-in-file (filename code-location debug-source)
651      "Resolve the source location for CODE-LOCATION in FILENAME."
652      (let* ((code-date (di:debug-source-created debug-source))
653             (source-code (or (source-cache-get filename code-date)
654                              (read-file filename))))
655        (make-location (list :file (unix-truename filename)) nil)
656        (with-input-from-string (s source-code)
657          (make-location (list :file (unix-truename filename))
658                         (list :position
659                               (1+ (code-location-stream-position
660                                    code-location s)))
661                         `(:snippet ,(read-snippet s))))))
663    (defun location-in-stream (code-location debug-source)
664      "Resolve the source location for a CODE-LOCATION from a stream.
665    This only succeeds if the code was compiled from an Emacs buffer."
666      (unless (debug-source-info-from-emacs-buffer-p debug-source)
667        (error "The code is compiled from a non-SLIME stream."))
668      (let* ((info (c::debug-source-info debug-source))
669             (string (getf info :emacs-buffer-string))
670             (position (code-location-string-offset
671                        code-location
672                        string)))
673        (make-location
674         (list :buffer (getf info :emacs-buffer))
675         (list :position (+ (getf info :emacs-buffer-offset) position))
676         (list :snippet (with-input-from-string (s string)
677                          (file-position s position)
678                          (read-snippet s))))))
680    (defun read-file (filename)
681      "Return the entire contents of FILENAME as a string."
682      (with-open-file (s filename :direction :input)
683        (let ((string (make-string (file-length s))))
684          (read-sequence string s)
685          string)))
687    (defun read-snippet (stream)
688      "Read a string of upto *SOURCE-SNIPPET-SIZE* characters from STREAM."
689      (read-upto-n-chars stream *source-snippet-size*))
691    (defun read-upto-n-chars (stream n)
692      "Return a string of upto N chars from STREAM."
693      (let* ((string (make-string n))
694             (chars  (read-sequence string stream)))
695        (subseq string 0 chars)))
697    ;;;;; Function-name locations
698    ;;;
699    (defun debug-info-function-name-location (debug-info)
700      "Return a function-name source-location for DEBUG-INFO.
701    Function-name source-locations are a fallback for when precise
702    positions aren't available."
703      (with-struct (c::debug-info- (fname name) source) debug-info
704        (with-struct (c::debug-source- info from name) (car source)
705          (ecase from
706            (:file
707             (make-location (list :file (namestring (truename name)))
708                            (list :function-name fname)))
709            (:stream
710             (assert (debug-source-info-from-emacs-buffer-p (car source)))
711             (make-location (list :buffer (getf info :emacs-buffer))
712                            (list :function-name fname)))
713            (:lisp
714             (make-location (list :source-form (princ-to-string (aref name 0)))
715                            (list :position 1)))))))
717    (defun debug-source-info-from-emacs-buffer-p (debug-source)
718      "Does the `info' slot of DEBUG-SOURCE contain an Emacs buffer location?
719    This is true for functions that were compiled directly from buffers."
720      (info-from-emacs-buffer-p (c::debug-source-info debug-source)))
722    (defun info-from-emacs-buffer-p (info)
723      (and info
724           (consp info)
725           (eq :emacs-buffer (car info))))
728    ;;;;; Groveling source-code for positions
730    (defun code-location-stream-position (code-location stream)
731      "Return the byte offset of CODE-LOCATION in STREAM.  Extract the
732    toplevel-form-number and form-number from CODE-LOCATION and use that
733    to find the position of the corresponding form.
735    Finish with STREAM positioned at the start of the code location."
736      (let* ((location (debug::maybe-block-start-location code-location))
737             (tlf-offset (di:code-location-top-level-form-offset location))
738             (form-number (di:code-location-form-number location)))
739        (let ((pos (form-number-stream-position tlf-offset form-number stream)))
740          (file-position stream pos)
741          pos)))
743    (defun form-number-stream-position (tlf-number form-number stream)
744      "Return the starting character position of a form in STREAM.
745    TLF-NUMBER is the top-level-form number.
746    FORM-NUMBER is an index into a source-path table for the TLF."
747      (let ((*read-suppress* t))
748        (dotimes (i tlf-number) (read stream))
749        (multiple-value-bind (tlf position-map) (read-and-record-source-map stream)
750          (let* ((path-table (di:form-number-translations tlf 0))
751                 (source-path
752                  (if (<= (length path-table) form-number) ; source out of sync?
753                      (list 0)              ; should probably signal a condition
754                      (reverse (cdr (aref path-table form-number))))))
755            (source-path-source-position source-path tlf position-map)))))
757    (defun code-location-string-offset (code-location string)
758      "Return the byte offset of CODE-LOCATION in STRING.
760      (with-input-from-string (s string)
761        (code-location-stream-position code-location s)))
763    ;;;;; Source-file cache
764    ;;;
765    ;;; To robustly find source locations it's useful to have the exact
766    ;;; source code that the loaded code was compiled from. In this source
767    ;;; we can accurately find the right location, and from that location
768    ;;; we can extract a "snippet" of code to show what the definition
769    ;;; looks like. Emacs can use this snippet in a best-match search to
770    ;;; locate the right definition, which works well even if the buffer
771    ;;; has been modified.
772    ;;;
773    ;;; The idea is that if a definition previously started with
774    ;;; `(define-foo bar' then it probably still does.
775    ;;;
776    ;;; Whenever we see that the file on disk has the same
777    ;;; `file-write-date' as a location we're looking for, we cache the
778    ;;; whole file inside Lisp. That way we will still have the matching
779    ;;; version even if the file is later modified on disk. If the file is
780    ;;; later recompiled and reloaded then we replace our cache entry.
782    (defvar *cache-sourcecode* t
783      "When true complete source files are cached.
784    The cache is used to keep known good copies of the source text which
785    correspond to the loaded code. Finding definitions is much more
786    reliable when the exact source is available, so we cache it in case it
787    gets edited on disk later.")
789    (defvar *source-file-cache* (make-hash-table :test 'equal)
790      "Cache of source file contents.
791    Maps from truename to source-cache-entry structure.")
793    (defstruct (source-cache-entry
794                 (:conc-name source-cache-entry.)
795                 (:constructor make-source-cache-entry (text date)))
796      text date)
798    (defun source-cache-get (filename date)
799      "Return the source code for FILENAME as written on DATE in a string.
800    Return NIL if the right version cannot be found."
801      (let ((entry (gethash filename *source-file-cache*)))
802        (cond ((and entry (equal date (source-cache-entry.date entry)))
803               ;; Cache hit.
804               (source-cache-entry.text entry))
805              ((or (null entry)
806                   (not (equal date (source-cache-entry.date entry))))
807               ;; Cache miss.
808               (if (equal (file-write-date filename) date)
809                   ;; File on disk has the correct version.
810                   (let ((source (read-file filename)))
811                     (setf (gethash filename *source-file-cache*)
812                           (make-source-cache-entry source date))
813                     source)
814                   nil)))))
816    (defun source-cached-p (filename)
817      "Is any version of FILENAME in the source cache?"
818      (if (gethash filename *source-file-cache*) t))
820    (defimplementation buffer-first-change (filename)
821      "Load a file into the cache when the user modifies its buffer.
822    This is a win if the user then saves the file and tries to M-. into it."
823      (unless (source-cached-p filename)
824        (ignore-errors (source-cache-get filename (file-write-date filename)))))
827    ;;;; Finding definitions
829    ;;; There are a great many different types of definition for us to
830    ;;; find. We search for definitions of every kind and return them in a
831    ;;; list.
833    (defimplementation find-definitions (name)
834      (append (function-definitions name)
835              (setf-definitions name)
836              (variable-definitions name)
837              (class-definitions name)
838              (type-definitions name)
839              (compiler-macro-definitions name)
840              (source-transform-definitions name)
841              (function-info-definitions name)
842              (ir1-translator-definitions name)))
844    ;;;;; Functions, macros, generic functions, methods
845    ;;;
846    ;;; We make extensive use of the compile-time debug information that
847    ;;; CMUCL records, in particular "debug functions" and "code
848    ;;; locations." Refer to the "Debugger Programmer's Interface" section
849    ;;; of the CMUCL manual for more details.
851    (defun function-definitions (name)
852      "Return definitions for NAME in the \"function namespace\", i.e.,
853    regular functions, generic functions, methods and macros.
854    NAME can any valid function name (e.g, (setf car))."
855      (let ((macro?    (and (symbolp name) (macro-function name)))
856            (special?  (and (symbolp name) (special-operator-p name)))
857            (function? (and (ext:valid-function-name-p name)
858                            (ext:info :function :definition name))))
859        (cond (macro?
860               (list `((defmacro ,name)
861                       ,(function-location (macro-function name)))))
862              (special?
863               (list `((:special-operator ,name)
864                       (:error ,(format nil "Special operator: ~S" name)))))
865              (function?
866               (let ((function (fdefinition name)))
867                 (if (genericp function)
868                     (generic-function-definitions name function)
869                     (list (list `(function ,name)
870                                 (function-location function)))))))))
872    ;;;;;; Ordinary (non-generic/macro/special) functions
873    ;;;
874    ;;; First we test if FUNCTION is a closure created by defstruct, and
875    ;;; if so extract the defstruct-description (`dd') from the closure
876    ;;; and find the constructor for the struct.  Defstruct creates a
877    ;;; defun for the default constructor and we use that as an
878    ;;; approximation to the source location of the defstruct.
879    ;;;
880    ;;; For an ordinary function we return the source location of the
881    ;;; first code-location we find.
882    ;;;
883    (defun function-location (function)
884      "Return the source location for FUNCTION."
885      (cond ((struct-closure-p function)
886             (struct-closure-location function))
887            ((c::byte-function-or-closure-p function)
888             (byte-function-location function))
889            (t
890             (compiled-function-location function))))
892    (defun compiled-function-location (function)
893      "Return the location of a regular compiled function."
894      (multiple-value-bind (code-location error)
895          (safe-definition-finding (function-first-code-location function))
896        (cond (error (list :error (princ-to-string error)))
897              (t (code-location-source-location code-location)))))
899  (defun function-first-code-location (function)  (defun function-first-code-location (function)
900      "Return the first code-location we can find for FUNCTION."
901    (and (function-has-debug-function-p function)    (and (function-has-debug-function-p function)
902         (di:debug-function-start-location         (di:debug-function-start-location
903          (di:function-debug-function function))))          (di:function-debug-function function))))
# Line 580  The second return value is the condition Line 910  The second return value is the condition
910             (vm::find-code-object function))             (vm::find-code-object function))
911         (not (eq closure function))))         (not (eq closure function))))
914    (defun byte-function-location (fn)
915      "Return the location of the byte-compiled function FN."
916      (etypecase fn
917        ((or c::hairy-byte-function c::simple-byte-function)
918         (let* ((component (c::byte-function-component fn))
919                (debug-info (kernel:%code-debug-info component)))
920           (debug-info-function-name-location debug-info)))
921        (c::byte-closure
922         (byte-function-location (c::byte-closure-function fn)))))
924    ;;; Here we deal with structure accessors. Note that `dd' is a
925    ;;; "defstruct descriptor" structure in CMUCL. A `dd' describes a
926    ;;; `defstruct''d structure.
928  (defun struct-closure-p (function)  (defun struct-closure-p (function)
929      "Is FUNCTION a closure created by defstruct?"
930    (or (function-code-object= function #'kernel::structure-slot-accessor)    (or (function-code-object= function #'kernel::structure-slot-accessor)
931        (function-code-object= function #'kernel::structure-slot-setter)        (function-code-object= function #'kernel::structure-slot-setter)
932        (function-code-object= function #'kernel::%defstruct)))        (function-code-object= function #'kernel::%defstruct)))
934    (defun struct-closure-location (function)
935      "Return the location of the structure that FUNCTION belongs to."
936      (assert (struct-closure-p function))
937      (safe-definition-finding
938        (dd-location (struct-closure-dd function))))
940  (defun struct-closure-dd (function)  (defun struct-closure-dd (function)
941      "Return the defstruct-definition (dd) of FUNCTION."
942    (assert (= (kernel:get-type function) vm:closure-header-type))    (assert (= (kernel:get-type function) vm:closure-header-type))
943    (flet ((find-layout (function)    (flet ((find-layout (function)
944             (sys:find-if-in-closure             (sys:find-if-in-closure
# Line 597  The second return value is the condition Line 950  The second return value is the condition
950                    (return-from find-layout value))))                    (return-from find-layout value))))
951              function)))              function)))
952      (kernel:layout-info (find-layout function))))      (kernel:layout-info (find-layout function))))
954  (defun dd-source-location (dd)  (defun dd-location (dd)
955      "Return the location of a `defstruct'."
956      ;; Find the location in a constructor.
957      (function-location (struct-constructor dd)))
959    (defun struct-constructor (dd)
960      "Return a constructor function from a defstruct definition.
961    Signal an error if no constructor can be found."
962    (let ((constructor (or (kernel:dd-default-constructor dd)    (let ((constructor (or (kernel:dd-default-constructor dd)
963                           (car (kernel::dd-constructors dd)))))                           (car (kernel::dd-constructors dd)))))
964      (when (or (not constructor) (and (consp constructor)      (when (or (null constructor)
965                                       (not (car constructor))))                (and (consp constructor) (null (car constructor))))
966        (error "Cannot locate struct without constructor: ~S"        (error "Cannot find structure's constructor: ~S"
967               (kernel::dd-name dd)))               (kernel::dd-name dd)))
968      (function-source-location      (coerce (if (consp constructor) (first constructor) constructor)
969       (coerce (if (consp constructor) (car constructor) constructor)              'function)))
970               'function))))  
971    ;;;;;; Generic functions and methods
973    (defun generic-function-definitions (name function)
974      "Return the definitions of a generic function and its methods."
975      (cons (list `(defgeneric ,name) (gf-location function))
976            (gf-method-definitions function)))
978    (defun gf-location (gf)
979      "Return the location of the generic function GF."
980      (definition-source-location gf (pcl::generic-function-name gf)))
982    (defun gf-method-definitions (gf)
983      "Return the locations of all methods of the generic function GF."
984      (mapcar #'method-definition (pcl::generic-function-methods gf)))
986    (defun method-definition (method)
987      (list (method-dspec method)
988            (method-location method)))
990    (defun method-dspec (method)
991      "Return a human-readable \"definition specifier\" for METHOD."
992      (let* ((gf (pcl:method-generic-function method))
993             (name (pcl:generic-function-name gf))
994             (specializers (pcl:method-specializers method))
995             (qualifiers (pcl:method-qualifiers method)))
996        `(method ,name ,@qualifiers ,(pcl::unparse-specializers specializers))))
998    ;; XXX maybe special case setters/getters
999    (defun method-location (method)
1000      (function-location (or (pcl::method-fast-function method)
1001                             (pcl:method-function method))))
1003  (defun genericp (fn)  (defun genericp (fn)
1004    (typep fn 'generic-function))    (typep fn 'generic-function))
1006  (defun gf-definition-location (gf)  ;;;;;; Types and classes
1007    (flet ((guess-source-file (faslfile)  
1008             (unix-truename  (defun type-definitions (name)
1009              (merge-pathnames (make-pathname :type "lisp")    "Return `deftype' locations for type NAME."
1010                               faslfile))))    (maybe-make-definition (ext:info :type :expander name) 'deftype name))
1011      (let ((def-source (pcl::definition-source gf))  
1012            (name (string (pcl:generic-function-name gf))))  (defun maybe-make-definition (function kind name)
1013        (etypecase def-source    "If FUNCTION is non-nil then return its definition location."
1014          (pathname (make-location    (if function
1015                     `(:file ,(guess-source-file def-source))        (list (list `(,kind ,name) (function-location function)))))
1016                     `(:function-name ,name)))  
1017          (cons  (defun class-definitions (name)
1018           (destructuring-bind ((dg name) pathname) def-source    "Return the definition locations for the class called NAME."
1019             (declare (ignore dg))    (if (symbolp name)
1020             (etypecase pathname        (let ((class (kernel::find-class name nil)))
1021               (pathname          (etypecase class
1022                (make-location `(:file ,(guess-source-file pathname))            (null '())
1023                               `(:function-name ,(string name)))))))))))            (kernel::structure-class
1024               (list (list `(defstruct ,name) (dd-location (find-dd name)))))
1025  (defun method-source-location (method)            #+(or)
1026    (function-source-location (or (pcl::method-fast-function method)            (conditions::condition-class
1027                                  (pcl:method-function method))))             (list (list `(define-condition ,name)
1028                           (condition-class-location class))))
1029  (defun gf-method-locations (gf)            (kernel::standard-class
1030    (let ((ms (pcl::generic-function-methods gf)))             (list (list `(defclass ,name)
1031      (mapcar #'method-source-location ms)))                         (class-location (find-class name)))))
1032              ((or kernel::built-in-class
1033  (defun gf-source-locations (gf)                 conditions::condition-class
1034    (list* (gf-definition-location gf)                 kernel:funcallable-structure-class)
1035           (gf-method-locations gf)))             (list (list `(kernel::define-type-class ,name)
1036                           `(:error
1037  (defun function-source-locations (function)                           ,(format nil "No source info for ~A" name)))))))))
1038    "Return a list of source locations for FUNCTION."  
1039    ;; First test if FUNCTION is a closure created by defstruct; if so  (defun class-location (class)
1040    ;; extract the defstruct-description (dd) from the closure and find    "Return the `defclass' location for CLASS."
1041    ;; the constructor for the struct.  Defstruct creates a defun for    (definition-source-location class (pcl:class-name class)))
1042    ;; the default constructor and we use that as an approximation to  
1043    ;; the source location of the defstruct.  (defun find-dd (name)
1044    ;;    "Find the defstruct-definition by the name of its structure-class."
1045    ;; For an ordinary function we return the source location of the    (let ((layout (ext:info :type :compiler-layout name)))
1046    ;; first code-location we find.      (if layout
1047    (cond ((struct-closure-p function)          (kernel:layout-info layout))))
1048           (list  
1049            (safe-definition-finding  (defun condition-class-location (class)
1050             (dd-source-location (struct-closure-dd function)))))    (let ((slots (conditions::condition-class-slots class))
1051          ((genericp function)          (name (conditions::condition-class-name class)))
1052           (gf-source-locations function))      (cond ((null slots)
1053          (t             `(:error ,(format nil "No location info for condition: ~A" name)))
1054           (list            (t
1055            (multiple-value-bind (code-location error)             ;; Find the class via one of its slot-reader methods.
1056                (safe-definition-finding (function-first-code-location function))             (let* ((slot (first slots))
1057              (cond (error (list :error (princ-to-string error)))                    (gf (fdefinition
1058                    (t (code-location-source-location code-location))))))))                         (first (conditions::condition-slot-readers slot)))))
1059                 (method-location
1060  (defun function-source-location (function)                (first
1061    (destructuring-bind (first) (function-source-locations function)                 (pcl:compute-applicable-methods-using-classes
1062      first))                  gf (list (find-class name))))))))))
1064  (defslimefun find-function-locations (symbol-name)  (defun make-name-in-file-location (file string)
1065    "Return a list of source-locations for SYMBOL-NAME's functions."    (multiple-value-bind (filename c)
1066    (multiple-value-bind (symbol foundp) (find-symbol-designator symbol-name)        (ignore-errors
1067      (cond ((not foundp)          (unix-truename (merge-pathnames (make-pathname :type "lisp")
1068             (list (list :error (format nil "Unkown symbol: ~A" symbol-name))))                                          file)))
1069            ((macro-function symbol)      (cond (filename (make-location `(:file ,filename)
1070             (function-source-locations (macro-function symbol)))                                     `(:function-name ,string)))
1071            ((special-operator-p symbol)            (t (list :error (princ-to-string c))))))
1072             (list (list :error (format nil "~A is a special-operator" symbol))))  
1073            ((fboundp symbol)  (defun source-location-form-numbers (location)
1074             (function-source-locations (coerce symbol 'function)))    (c::decode-form-numbers (c::form-numbers-form-numbers location)))
1075            (t (list (list :error  
1076                           (format nil "Symbol not fbound: ~A" symbol-name))))  (defun source-location-tlf-number (location)
1077            )))    (nth-value 0 (source-location-form-numbers location)))
1079    (defun source-location-form-number (location)
1080      (nth-value 1 (source-location-form-numbers location)))
1082    (defun resolve-file-source-location (location)
1083      (let ((filename (c::file-source-location-pathname location))
1084            (tlf-number (source-location-tlf-number location))
1085            (form-number (source-location-form-number location)))
1086        (with-open-file (s filename)
1087          (let ((pos (form-number-stream-position tlf-number form-number s)))
1088            (make-location `(:file ,(unix-truename filename))
1089                           `(:position ,(1+ pos)))))))
1091    (defun resolve-stream-source-location (location)
1092      (let ((info (c::stream-source-location-user-info location))
1093            (tlf-number (source-location-tlf-number location))
1094            (form-number (source-location-form-number location)))
1095        ;; XXX duplication in frame-source-location
1096        (assert (info-from-emacs-buffer-p info))
1097        (destructuring-bind (&key emacs-buffer emacs-buffer-string
1098                                  emacs-buffer-offset) info
1099          (with-input-from-string (s emacs-buffer-string)
1100            (let ((pos (form-number-stream-position tlf-number form-number s)))
1101              (make-location `(:buffer ,emacs-buffer)
1102                             `(:position ,(+ emacs-buffer-offset pos))))))))
1104    ;; XXX predicates for 18e backward compatibilty.  Remove them when
1105    ;; we're 19a only.
1106    (defun file-source-location-p (object)
1107      (when (fboundp 'c::file-source-location-p)
1108        (c::file-source-location-p object)))
1110    (defun stream-source-location-p (object)
1111      (when (fboundp 'c::stream-source-location-p)
1112        (c::stream-source-location-p object)))
1114    (defun source-location-p (object)
1115      (or (file-source-location-p object)
1116          (stream-source-location-p object)))
1118    (defun resolve-source-location (location)
1119      (etypecase location
1120        ((satisfies file-source-location-p)
1121         (resolve-file-source-location location))
1122        ((satisfies stream-source-location-p)
1123         (resolve-stream-source-location location))))
1125    (defun definition-source-location (object name)
1126      (let ((source (pcl::definition-source object)))
1127        (etypecase source
1128          (null
1129           `(:error ,(format nil "No source info for: ~A" object)))
1130          ((satisfies source-location-p)
1131           (resolve-source-location source))
1132          (pathname
1133           (make-name-in-file-location source name))
1134          (cons
1135           (destructuring-bind ((dg name) pathname) source
1136             (declare (ignore dg))
1137             (etypecase pathname
1138               (pathname (make-name-in-file-location pathname (string name)))
1139               (null `(:error ,(format nil "Cannot resolve: ~S" source)))))))))
1141    (defun setf-definitions (name)
1142      (let ((function (or (ext:info :setf :inverse name)
1143                          (ext:info :setf :expander name))))
1144        (if function
1145            (list (list `(setf ,name)
1146                        (function-location (coerce function 'function)))))))
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)))))
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)))))))
1165    (defun compiler-macro-definitions (symbol)
1166      (maybe-make-definition (compiler-macro-function symbol)
1167                             'define-compiler-macro
1168                             symbol))
1170    (defun source-transform-definitions (name)
1171      (maybe-make-definition (ext:info :function :source-transform name)
1172                             'c:def-source-transform
1173                             name))
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))))))))
1198    (defun ir1-translator-definitions (name)
1199      (maybe-make-definition (ext:info :function :ir1-convert name)
1200                             'c:def-ir1-translator name))
1203  ;;;; Documentation.  ;;;; Documentation.
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 734  The second return value is the condition Line 1248  The second return value is the condition
1248                         (doc nil)))                         (doc nil)))
1249        result)))        result)))
1251  (defslimefun describe-setf-function (symbol-name)  (defimplementation describe-definition (symbol namespace)
1252    (print-description-to-string    (describe (ecase namespace
1253     (or (ext:info setf inverse (from-string symbol-name))                (:variable
1254         (ext:info setf expander (from-string symbol-name)))))                 symbol)
1255                  ((:function :generic-function)
1256  (defslimefun describe-type (symbol-name)                 (symbol-function symbol))
1257    (print-description-to-string                (:setf
1258     (kernel:values-specifier-type (from-string symbol-name))))                 (or (ext:info setf inverse symbol)
1259                       (ext:info setf expander symbol)))
1260  (defslimefun describe-class (symbol-name)                (:type
1261    (print-description-to-string (find-class (from-string symbol-name) nil)))                 (kernel:values-specifier-type symbol))
1262                  (:class
1263  (defslimefun describe-alien-type (symbol-name)                 (find-class symbol))
1264    (let ((name (from-string symbol-name)))                (:alien-struct
1265      (ecase (ext:info :alien-type :kind name)                 (ext:info :alien-type :struct symbol))
1266        (:primitive                (:alien-union
1267         (print-description-to-string                 (ext:info :alien-type :union symbol))
1268          (let ((alien::*values-type-okay* t))                (:alien-enum
1269            (funcall (ext:info :alien-type :translator name) (list name)))))                 (ext:info :alien-type :enum symbol))
1270        ((:defined)                (:alien-type
1271         (print-description-to-string (ext:info :alien-type :definition name)))                 (ecase (ext:info :alien-type :kind symbol)
1272        (:unknown                   (:primitive
1273         (format nil "Unkown alien type: ~A" symbol-name)))))                    (let ((alien::*values-type-okay* t))
1274                        (funcall (ext:info :alien-type :translator symbol)
1275  (defmacro %describe-alien (symbol-name namespace)                               (list symbol))))
1276    `(print-description-to-string                   ((:defined)
1277      (ext:info :alien-type ,namespace (from-string ,symbol-name))))                    (ext:info :alien-type :definition symbol))
1278                     (:unknown
1279  (defslimefun describe-alien-struct (symbol-name)                    (return-from describe-definition
1280    (%describe-alien symbol-name :struct))                      (format nil "Unknown alien type: ~S" symbol))))))))
1282  (defslimefun describe-alien-union (symbol-name)  ;;;;; Argument lists
1283    (%describe-alien symbol-name :union))  
1284    (defimplementation arglist (symbol)
1285  (defslimefun describe-alien-enum (symbol-name)    (let* ((fun (or (macro-function symbol)
1286    (%describe-alien symbol-name :enum))                    (symbol-function symbol)))
1287             (arglist
1288  (defmethod arglist-string (fname)            (cond ((eval:interpreted-function-p fun)
1289    "Return a string describing the argument list for FNAME.                   (eval:interpreted-function-arglist fun))
1290  The result has the format \"(...)\"."                  ((pcl::generic-function-p fun)
1291    (declare (type string fname))                   (pcl:generic-function-lambda-list fun))
1292    (multiple-value-bind (function condition)                  ((c::byte-function-or-closure-p fun)
1293        (ignore-errors (values (find-symbol-designator fname *buffer-package*)))                   (byte-code-function-arglist fun))
1294      (when condition                  ((kernel:%function-arglist (kernel:%function-self fun))
1295        (return-from arglist-string (format nil "(-- ~A)" condition)))                   (handler-case (read-arglist fun)
1296      (let ((arglist                       (error () :not-available)))
1297             (if (not (or (fboundp function)                  ;; this should work both for compiled-debug-function
1298                          (functionp function)))                  ;; and for interpreted-debug-function
1299                 "(-- <Unknown-Function>)"                  (t
1300                 (let* ((fun (or (macro-function function)                   (handler-case (debug-function-arglist
1301                                 (symbol-function function)))                                  (di::function-debug-function fun))
1302                        (df (di::function-debug-function fun))                     (di:unhandled-condition () :not-available))))))
1303                        (arglist (kernel:%function-arglist fun)))      (check-type arglist (or list (member :not-available)))
1304                   (cond ((eval:interpreted-function-p fun)      arglist))
1305                          (eval:interpreted-function-arglist fun))  
1306                         ((pcl::generic-function-p fun)  ;;; A simple case: the arglist is available as a string that we can
1307                          (pcl::gf-pretty-arglist fun))  ;;; `read'.
1308                         (arglist arglist)  
1309                         ;; this should work both for  (defun read-arglist (fn)
1310                         ;; compiled-debug-function and for    "Parse the arglist-string of the function object FN."
1311                         ;; interpreted-debug-function    (let ((string (kernel:%function-arglist
1312                         (df (di::debug-function-lambda-list df))                   (kernel:%function-self fn)))
1313                         (t "(<arglist-unavailable>)"))))))          (package (find-package
1314        (if (stringp arglist)                    (c::compiled-debug-info-package
1315            arglist                     (kernel:%code-debug-info
1316            (to-string arglist)))))                      (vm::find-code-object fn))))))
1317        (with-standard-io-syntax
1318          (let ((*package* (or package *package*)))
1319            (read-from-string string)))))
1321    ;;; A harder case: an approximate arglist is derived from available
1322    ;;; debugging information.
1324    (defun debug-function-arglist (debug-function)
1325      "Derive the argument list of DEBUG-FUNCTION from debug info."
1326      (let ((args (di::debug-function-lambda-list debug-function))
1327            (required '())
1328            (optional '())
1329            (rest '())
1330            (key '()))
1331        ;; collect the names of debug-vars
1332        (dolist (arg args)
1333          (etypecase arg
1334            (di::debug-variable
1335             (push (di::debug-variable-symbol arg) required))
1336            ((member :deleted)
1337             (push ':deleted required))
1338            (cons
1339             (ecase (car arg)
1340               (:keyword
1341                (push (second arg) key))
1342               (:optional
1343                (push (debug-variable-symbol-or-deleted (second arg)) optional))
1344               (:rest
1345                (push (debug-variable-symbol-or-deleted (second arg)) rest))))))
1346        ;; intersperse lambda keywords as needed
1347        (append (nreverse required)
1348                (if optional (cons '&optional (nreverse optional)))
1349                (if rest (cons '&rest (nreverse rest)))
1350                (if key (cons '&key (nreverse key))))))
1352    (defun debug-variable-symbol-or-deleted (var)
1353      (etypecase var
1354        (di:debug-variable
1355         (di::debug-variable-symbol var))
1356        ((member :deleted)
1357         '#:deleted)))
1359    (defun symbol-debug-function-arglist (fname)
1360      "Return FNAME's debug-function-arglist and %function-arglist.
1361    A utility for debugging DEBUG-FUNCTION-ARGLIST."
1362      (let ((fn (fdefinition fname)))
1363        (values (debug-function-arglist (di::function-debug-function fn))
1364                (kernel:%function-arglist (kernel:%function-self fn)))))
1366    ;;; Deriving arglists for byte-compiled functions:
1367    ;;;
1368    (defun byte-code-function-arglist (fn)
1369      ;; There doesn't seem to be much arglist information around for
1370      ;; byte-code functions.  Use the arg-count and return something like
1371      ;; (arg0 arg1 ...)
1372      (etypecase fn
1373        (c::simple-byte-function
1374         (loop for i from 0 below (c::simple-byte-function-num-args fn)
1375               collect (make-arg-symbol i)))
1376        (c::hairy-byte-function
1377         (hairy-byte-function-arglist fn))
1378        (c::byte-closure
1379         (byte-code-function-arglist (c::byte-closure-function fn)))))
1381    (defun make-arg-symbol (i)
1382      (make-symbol (format nil "~A~D" (string 'arg) i)))
1384    ;;; A "hairy" byte-function is one that takes a variable number of
1385    ;;; arguments. `hairy-byte-function' is a type from the bytecode
1386    ;;; interpreter.
1387    ;;;
1388    (defun hairy-byte-function-arglist (fn)
1389      (let ((counter -1))
1390        (flet ((next-arg () (make-arg-symbol (incf counter))))
1391          (with-struct (c::hairy-byte-function- min-args max-args rest-arg-p
1392                                                keywords-p keywords) fn
1393            (let ((arglist '())
1394                  (optional (- max-args min-args)))
1395              ;; XXX isn't there a better way to write this?
1396              ;; (Looks fine to me. -luke)
1397              (dotimes (i min-args)
1398                (push (next-arg) arglist))
1399              (when (plusp optional)
1400                (push '&optional arglist)
1401                (dotimes (i optional)
1402                  (push (next-arg) arglist)))
1403              (when rest-arg-p
1404                (push '&rest arglist)
1405                (push (next-arg) arglist))
1406              (when keywords-p
1407                (push '&key arglist)
1408                (loop for (key _ __) in keywords
1409                      do (push key arglist))
1410                (when (eq keywords-p :allow-others)
1411                  (push '&allow-other-keys arglist)))
1412              (nreverse arglist))))))
1415  ;;;; Miscellaneous.  ;;;; Miscellaneous.
1417  (defmethod macroexpand-all (form)  (defimplementation macroexpand-all (form)
1418    (walker:macroexpand-all form))    (walker:macroexpand-all form))
1420  (defun tracedp (fname)  (defimplementation set-default-directory (directory)
   (gethash (debug::trace-fdefinition fname)  
 (defslimefun toggle-trace-fdefinition (fname-string)  
   (let ((fname (from-string fname-string)))  
     (cond ((tracedp fname)  
            (debug::untrace-1 fname)  
            (format nil "~S is now untraced." fname))  
            (debug::trace-1 fname (debug::make-trace-info))  
            (format nil "~S is now traced." fname)))))  
 (defslimefun set-default-directory (directory)  
1421    (setf (ext:default-directory) (namestring directory))    (setf (ext:default-directory) (namestring directory))
1422    ;; Setting *default-pathname-defaults* to an absolute directory    ;; Setting *default-pathname-defaults* to an absolute directory
1423    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.    ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
1424    (setf *default-pathname-defaults* (pathname (ext:default-directory)))    (setf *default-pathname-defaults* (pathname (ext:default-directory)))
1425    (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)))))  
 (defun make-source-map ()  
   (make-hash-table :test #'eq))  
 (defvar *source-map* (make-source-map)  
   "The hashtable table used for source position recording.")  
 (defvar *recording-readtable-cache* '()  
   "An alist of (READTABLE . RECORDING-READTABLE) pairs.")  
 (defun lookup-recording-readtable (readtable)  
   "Find a cached or create a new recording readtable for READTABLE."  
   (or (cdr (assoc readtable *recording-readtable-cache*))  
       (let ((table (make-source-recording-readtable readtable *source-map*)))  
         (push (cons readtable table) *recording-readtable-cache*)  
 (defun read-and-record-source-map (stream)  
   "Read the next object from STREAM.  
 Return the object together with a hashtable that maps  
 subexpressions of the object to stream positions."  
   (let ((*readtable* (lookup-recording-readtable *readtable*)))  
     (clrhash *source-map*)  
     (values (read stream) *source-map*)))  
 (defun source-path-stream-position (path stream)  
   "Search the source-path PATH in STREAM and return its position."  
   (destructuring-bind (tlf-number . path) path  
     (let ((*read-suppress* t))  
       (dotimes (i tlf-number) (read stream))  
       (multiple-value-bind (form source-map)  
           (read-and-record-source-map stream)  
         (source-path-source-position (cons 0 path) form source-map)))))  
 (defun source-path-string-position (path string)  
   (with-input-from-string (s string)  
     (source-path-stream-position path s)))  
1427  (defun source-path-file-position (path filename)  (defimplementation default-directory ()
1428    (with-open-file (file filename)    (namestring (ext:default-directory)))
     (source-path-stream-position path file)))  
 (defun source-path-source-position (path form source-map)  
   "Return the start position of PATH form FORM and SOURCE-MAP.  All  
 subforms along the path are considered and the start and end position  
 of deepest (i.e. smallest) possible form is returned."  
   ;; compute all subforms along path  
   (let ((forms (loop for n in path  
                      for f = form then (nth n f)  
                      collect f)))  
     ;; select the first subform present in source-map  
     (loop for form in (reverse forms)  
           for positions = (gethash form source-map)  
           until (and positions (null (cdr positions)))  
           finally (destructuring-bind ((start . end)) positions  
                     (return (values (1- start) end))))))  
 (defun code-location-stream-position (code-location stream)  
   "Return the byte offset of CODE-LOCATION in STREAM.  Extract the  
 toplevel-form-number and form-number from CODE-LOCATION and use that  
 to find the position of the corresponding form."  
   (let* ((location (debug::maybe-block-start-location code-location))  
          (tlf-offset (di:code-location-top-level-form-offset location))  
          (form-number (di:code-location-form-number location))  
          (*read-suppress* t))  
     (dotimes (i tlf-offset) (read stream))  
     (multiple-value-bind (tlf position-map) (read-and-record-source-map stream)  
       (let* ((path-table (di:form-number-translations tlf 0))  
               (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)))  
1430  (defun code-location-file-position (code-location filename)  (defimplementation call-without-interrupts (fn)
1431    (with-open-file (s filename :direction :input)    (sys:without-interrupts (funcall fn)))
     (code-location-stream-position code-location s)))  
1433  (defun debug-source-info-from-emacs-buffer-p (debug-source)  (defimplementation getpid ()
1434    (let ((info (c::debug-source-info debug-source)))    (unix:unix-getpid))
     (and info  
          (consp info)  
          (eq :emacs-buffer (car info)))))  
1436  (defun source-location-from-code-location (code-location)  (defimplementation lisp-implementation-type-name ()
1437    "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  
        (make-location (list :file (unix-truename name))  
                       (list :position (1+ (code-location-file-position  
                                            code-location name)))))  
        (assert (debug-source-info-from-emacs-buffer-p debug-source))  
        (let ((info (c::debug-source-info debug-source)))  
           (list :buffer (getf info :emacs-buffer))  
           (list :position (+ (getf info :emacs-buffer-offset)  
                               (getf info :emacs-buffer-string)))))))  
         (list :source-form (with-output-to-string (*standard-output*)  
                               code-location 100 t)))  
         (list :position 1))))))  
1439  (defun code-location-source-location (code-location)  (defimplementation quit-lisp ()
1440    "Safe wrapper around `code-location-from-source-location'."    (ext::quit))
    (source-location-from-code-location code-location)))  
1442  (defslimefun getpid ()  ;;; source-path-{stream,file,string,etc}-position moved into
1443    (unix:unix-getpid))  ;;; swank-source-path-parser
1446  ;;;; Debugging  ;;;; Debugging
1448  (defvar *sldb-stack-top*)  (defvar *sldb-stack-top*)
 (defvar *sldb-restarts*)  
1450  (defmethod call-with-debugging-environment (debugger-loop-fn)  (defimplementation call-with-debugging-environment (debugger-loop-fn)
1451    (unix:unix-sigsetmask 0)    (unix:unix-sigsetmask 0)
1452    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))    (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
1453           (*sldb-restarts* (compute-restarts *swank-debugger-condition*))           (debug:*stack-top-hint* nil))
1454           (debug:*stack-top-hint* nil)      (handler-bind ((di::unhandled-condition
          (*debugger-hook* nil)  
          (*readtable* (or debug:*debug-readtable* *readtable*))  
          (*print-level* debug:*debug-print-level*)  
          (*print-length* debug:*debug-print-length*)  
          (*print-readably* nil))  
     (handler-bind ((di:debug-condition  
1455                      (lambda (condition)                      (lambda (condition)
1456                        (signal (make-condition                        (error (make-condition
1457                                 'sldb-condition                                'sldb-condition
1458                                 :original-condition condition)))))                                :original-condition condition)))))
1459        (funcall debugger-loop-fn))))        (funcall debugger-loop-fn))))
1461  (defun format-restarts-for-emacs ()  (defun frame-down (frame)
1462    "Return a list of restarts for *swank-debugger-condition* in a    (handler-case (di:frame-down frame)
1463  format suitable for Emacs."      (di:no-debug-info () nil)))
   (loop for restart in *sldb-restarts*  
         collect (list (princ-to-string (restart-name restart))  
                       (princ-to-string restart))))  
 (defun format-condition-for-emacs ()  
   (format nil "~A~%   [Condition of type ~S]"  
           (debug::safe-condition-message *swank-debugger-condition*)  
           (type-of *swank-debugger-condition*)))  
1465  (defun nth-frame (index)  (defun nth-frame (index)
1466    (do ((frame *sldb-stack-top* (di:frame-down frame))    (do ((frame *sldb-stack-top* (frame-down frame))
1467         (i index (1- i)))         (i index (1- i)))
1468        ((zerop i) frame)))        ((zerop i) frame)))
1470  (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  
1471    (let ((end (or end most-positive-fixnum)))    (let ((end (or end most-positive-fixnum)))
1472      (loop for f = (nth-frame start) then (di:frame-down f)      (loop for f = (nth-frame start) then (frame-down f)
1473            for i from start below end            for i from start below end
1474            while f            while f
1475            collect f)))            collect f)))
1477  (defmethod backtrace (start end)  (defimplementation print-frame (frame stream)
1478    (mapcar #'format-frame-for-emacs (compute-backtrace start end)))    (let ((*standard-output* stream))
1479        (debug::print-frame-call frame :verbosity 1 :number nil)))
1481  (defmethod debugger-info-for-emacs (start end)  (defimplementation frame-source-location-for-emacs (index)
   (list (format-condition-for-emacs)  
         (backtrace start end)))  
 (defmethod frame-source-location-for-emacs (index)  
1482    (code-location-source-location (di:frame-code-location (nth-frame index))))    (code-location-source-location (di:frame-code-location (nth-frame index))))
1484  (defmethod eval-in-frame (form index)  (defimplementation eval-in-frame (form index)
1485    (di:eval-in-frame (nth-frame index) form))    (di:eval-in-frame (nth-frame index) form))
1487  (defslimefun pprint-eval-string-in-frame (string index)  (defun frame-debug-vars (frame)
1488    (swank-pprint    "Return a vector of debug-variables in frame."
1489     (multiple-value-list    (di::debug-function-debug-variables (di:frame-debug-function frame)))
1490      (di:eval-in-frame (nth-frame index) (from-string string)))))  
1491    (defun debug-var-value (var frame location)
1492  (defslimefun inspect-in-frame (string index)    (ecase (di:debug-variable-validity var location)
1493    (reset-inspector)      (:valid (di:debug-variable-value var frame))
1494    (inspect-object (di:eval-in-frame (nth-frame index) (from-string string))))      ((:invalid :unknown) ':<not-available>)))
1496  (defmethod frame-locals (index)  (defimplementation frame-locals (index)
1497    (let* ((frame (nth-frame index))    (let* ((frame (nth-frame index))
1498           (location (di:frame-code-location frame))           (loc (di:frame-code-location frame))
1499           (debug-function (di:frame-debug-function frame))           (vars (frame-debug-vars frame)))
1500           (debug-variables (di::debug-function-debug-variables debug-function)))      (loop for v across vars collect
1501      (loop for v across debug-variables            (list :name (di:debug-variable-symbol v)
1502            collect (list                  :id (di:debug-variable-id v)
1503                     :symbol (di:debug-variable-symbol v)                  :value (debug-var-value v frame loc)))))
1504                     :id (di:debug-variable-id v)  
1505                     :value-string  (defimplementation frame-var-value (frame var)
1506                     (if (eq (di:debug-variable-validity v location)    (let* ((frame (nth-frame frame))
1507                             :valid)           (dvar (aref (frame-debug-vars frame) var)))
1508                         (to-string (di:debug-variable-value v frame))      (debug-var-value dvar frame (di:frame-code-location frame))))
1509                         "<not-available>")))))  
1510    (defimplementation frame-catch-tags (index)
1511  (defmethod frame-catch-tags (index)    (mapcar #'car (di:frame-catches (nth-frame index))))
1512    (loop for (tag . code-location) in (di:frame-catches (nth-frame index))  
1513          collect `(,tag . ,(code-location-source-location code-location))))  (defun set-step-breakpoints (frame)
1514      (when (di:debug-block-elsewhere-p (di:code-location-debug-block
1515  (defslimefun invoke-nth-restart (index)                                       (di:frame-code-location frame)))
1516    (invoke-restart-interactively (nth-restart index)))      (error "Cannot step, in elsewhere code~%"))
1517      (let* ((code-location (di:frame-code-location frame))
1518             (debug::*bad-code-location-types*
1519              (remove :call-site debug::*bad-code-location-types*))
1520             (next (debug::next-code-locations code-location)))
1521        (cond (next
1522               (let ((steppoints '()))
1523                 (flet ((hook (frame breakpoint)
1524                          (let ((debug:*stack-top-hint* frame))
1525                            (mapc #'di:delete-breakpoint steppoints)
1526                            (let ((cl (di::breakpoint-what breakpoint)))
1527                              (break "Breakpoint: ~S ~S"
1528                                     (di:code-location-kind cl)
1529                                     (di::compiled-code-location-pc cl))))))
1530                   (dolist (code-location next)
1531                     (let ((bp (di:make-breakpoint #'hook code-location
1532                                                   :kind :code-location)))
1533                       (di:activate-breakpoint bp)
1534                       (push bp steppoints))))))
1535             (t
1536              (flet ((hook (frame breakpoint values cookie)
1537                       (declare (ignore cookie))
1538                       (di:delete-breakpoint breakpoint)
1539                       (let ((debug:*stack-top-hint* frame))
1540                         (break "Function-end: ~A ~A" breakpoint values))))
1541                (let* ((debug-function (di:frame-debug-function frame))
1542                       (bp (di:make-breakpoint #'hook debug-function
1543                                               :kind :function-end)))
1544                  (di:activate-breakpoint bp)))))))
1546    (defimplementation sldb-step (frame)
1547      (cond ((find-restart 'continue)
1548             (set-step-breakpoints (nth-frame frame))
1549             (continue))
1550            (t
1551             (error "No continue restart."))))
1553  (defslimefun sldb-abort ()  (defun frame-cfp (frame)
1554    (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))    "Return the Control-Stack-Frame-Pointer for FRAME."
1555      (etypecase frame
1556        (di::compiled-frame (di::frame-pointer frame))
1557        ((or di::interpreted-frame null) -1)))
1559    (defun frame-ip (frame)
1560      "Return the (absolute) instruction pointer and the relative pc of FRAME."
1561      (if (not frame)
1562          -1
1563          (let ((debug-fun (di::frame-debug-function frame)))
1564            (etypecase debug-fun
1565              (di::compiled-debug-function
1566               (let* ((code-loc (di:frame-code-location frame))
1567                      (component (di::compiled-debug-function-component debug-fun))
1568                      (pc (di::compiled-code-location-pc code-loc))
1569                      (ip (sys:without-gcing
1570                           (sys:sap-int
1571                            (sys:sap+ (kernel:code-instructions component) pc)))))
1572                 (values ip pc)))
1573              ((or di::bogus-debug-function di::interpreted-debug-function)
1574               -1)))))
1576    (defun frame-registers (frame)
1577      "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
1578      (let* ((cfp (frame-cfp frame))
1579             (csp (frame-cfp (di::frame-up frame)))
1580             (ip (frame-ip frame))
1581             (ocfp (frame-cfp (di::frame-down frame)))
1582             (lra (frame-ip (di::frame-down frame))))
1583        (values csp cfp ip ocfp lra)))
1585    (defun print-frame-registers (frame-number)
1586      (let ((frame (di::frame-real-frame (nth-frame frame-number))))
1587        (flet ((fixnum (p) (etypecase p
1588                             (integer p)
1589                             (sys:system-area-pointer (sys:sap-int p)))))
1590          (apply #'format t "~
1591    CSP  =  ~X
1592    CFP  =  ~X
1593    IP   =  ~X
1594    OCFP =  ~X
1595    LRA  =  ~X~%" (mapcar #'fixnum
1596                          (multiple-value-list (frame-registers frame)))))))
1599    (defimplementation disassemble-frame (frame-number)
1600      "Return a string with the disassembly of frames code."
1601      (print-frame-registers frame-number)
1602      (terpri)
1603      (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
1604             (debug-fun (di::frame-debug-function frame)))
1605        (etypecase debug-fun
1606          (di::compiled-debug-function
1607           (let* ((component (di::compiled-debug-function-component debug-fun))
1608                  (fun (di:debug-function-function debug-fun)))
1609             (if fun
1610                 (disassemble fun)
1611                 (disassem:disassemble-code-component component))))
1612          (di::bogus-debug-function
1613           (format t "~%[Disassembling bogus frames not implemented]")))))
1616  ;;;; Inspecting  ;;;; Inspecting
 (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)  
   (inspect-object (eval (from-string string))))  
 (defun print-part-to-string (value)  
   (let ((*print-pretty* nil))  
     (let ((string (to-string value))  
           (pos (position value *inspector-history*)))  
       (if pos  
           (format nil "#~D=~A" pos string)  
 (defun inspect-object (object)  
   (push (setq *inspectee* object) *inspector-stack*)  
   (unless (find object *inspector-history*)  
     (vector-push-extend object *inspector-history*))  
   (multiple-value-bind (text parts) (inspected-parts object)  
     (setq *inspectee-parts* parts)  
       (list :text text  
             :type (to-string (type-of object))  
             :primitive-type (describe-primitive-type object)  
             :parts (loop for (label . value) in parts  
                          collect (cons label  
                                        (print-part-to-string value))))))  
1618  (defconstant +lowtag-symbols+  (defconstant +lowtag-symbols+
1619    '(vm:even-fixnum-type    '(vm:even-fixnum-type
1620      vm:function-pointer-type      vm:function-pointer-type
# Line 1152  stack." Line 1623  stack."
1623      vm:odd-fixnum-type      vm:odd-fixnum-type
1624      vm:instance-pointer-type      vm:instance-pointer-type
1625      vm:other-immediate-1-type      vm:other-immediate-1-type
1626      vm:other-pointer-type))      vm:other-pointer-type)
1627      "Names of the constants that specify type tags.
1628    The `symbol-value' of each element is a type tag.")
1630  (defconstant +header-type-symbols+  (defconstant +header-type-symbols+
1631    ;; Is there a convinient place for all those constants?    (flet ((suffixp (suffix string)
1632    (flet ((tail-comp (string tail)             (and (>= (length string) (length suffix))
1633             (and (>= (length string) (length tail))                  (string= string suffix :start1 (- (length string)
1634                  (string= string tail :start1 (- (length string)                                                    (length suffix))))))
1635                                                  (length tail))))))      ;; Is there a convinient place for all those constants?
1636      (remove-if-not      (remove-if-not
1637       (lambda (x) (and (tail-comp (symbol-name x) "-TYPE")       (lambda (x) (and (suffixp "-TYPE" (symbol-name x))
1638                        (not (member x +lowtag-symbols+))                        (not (member x +lowtag-symbols+))
1639                        (boundp x)                        (boundp x)
1640                        (typep (symbol-value x) 'fixnum)))                        (typep (symbol-value x) 'fixnum)))
1641       (append (apropos-list "-TYPE" "VM" t)       (append (apropos-list "-TYPE" "VM" t)
1642               (apropos-list "-TYPE" "BIGNUM" t)))))               (apropos-list "-TYPE" "BIGNUM" t))))
1643      "A list of names of the type codes in boxed objects.")
1645  (defun describe-primitive-type (object)  (defimplementation describe-primitive-type (object)
1646    (with-output-to-string (*standard-output*)    (with-output-to-string (*standard-output*)
1647      (let* ((lowtag (kernel:get-lowtag object))      (let* ((lowtag (kernel:get-lowtag object))
1648             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))             (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
1649        (format t "[lowtag: ~A" lowtag-symbol)        (format t "lowtag: ~A" lowtag-symbol)
1650        (cond ((member lowtag (list vm:other-pointer-type        (when (member lowtag (list vm:other-pointer-type
1651                                    vm:function-pointer-type                                   vm:function-pointer-type
1652                                    vm:other-immediate-0-type                                   vm:other-immediate-0-type
1653                                    vm:other-immediate-1-type                                   vm:other-immediate-1-type
1654                                    ))                                   ))
1655               (let* ((type (kernel:get-type object))          (let* ((type (kernel:get-type object))
1656                      (type-symbol (find type +header-type-symbols+                 (type-symbol (find type +header-type-symbols+
1657                                         :key #'symbol-value)))                                    :key #'symbol-value)))
1658                 (format t ", type: ~A]" type-symbol)))            (format t ", type: ~A" type-symbol))))))
             (t (format t "]"))))))  
 (defun nth-part (index)  
   (cdr (nth index *inspectee-parts*)))  
 (defslimefun inspect-nth-part (index)  
   (inspect-object (nth-part index)))  
 (defslimefun inspector-pop ()  
   "Drop the inspector stack and inspect the second element.  Return  
 nil if there's no second element."  
   (cond ((cdr *inspector-stack*)  
          (pop *inspector-stack*)  
          (inspect-object (pop *inspector-stack*)))  
         (t nil)))  
 (defslimefun inspector-next ()  
   "Inspect the next element in the *inspector-history*."  
   (let ((position (position *inspectee* *inspector-history*)))  
     (cond ((= (1+ position) (length *inspector-history*))  
           (t (inspect-object (aref *inspector-history* (1+ position)))))))  
 (defslimefun quit-inspector ()  
 (defslimefun describe-inspectee ()  
   "Describe the currently inspected object."  
   (print-description-to-string *inspectee*))  
 (defgeneric inspected-parts (object)  
    "Return a short description and a list of (label . value) pairs."))  
1660  (defmethod inspected-parts (o)  (defimplementation inspected-parts (o)
1661    (cond ((di::indirect-value-cell-p o)    (cond ((di::indirect-value-cell-p o)
1662           (inspected-parts-of-value-cell o))           (inspected-parts-of-value-cell o))
1663          (t          (t
# Line 1235  nil if there's no second element." Line 1675  nil if there's no second element."
1675    (values (format nil "~A~% is a value cell." o)    (values (format nil "~A~% is a value cell." o)
1676            (list (cons "Value" (c:value-cell-ref o)))))            (list (cons "Value" (c:value-cell-ref o)))))
 ;; borrowed from sbcl  
 (defmethod inspected-parts ((object cons))  
   (if (consp (cdr object))  
       (inspected-parts-of-nontrivial-list object)  
       (inspected-parts-of-simple-cons object)))  
 (defun inspected-parts-of-simple-cons (object)  
   (values "The object is a CONS."  
           (list (cons (string 'car) (car object))  
                 (cons (string 'cdr) (cdr object)))))  
 (defun inspected-parts-of-nontrivial-list (object)  
   (let ((length 0)  
         (in-list object)  
         (reversed-elements nil))  
     (flet ((done (description-format)  
              (return-from inspected-parts-of-nontrivial-list  
                (values (format nil description-format length)  
                        (nreverse reversed-elements)))))  
        (cond ((null in-list)  
               (done "The object is a proper list of length ~S.~%"))  
              ((>= length *inspect-length*)  
               (push (cons  (string 'rest) in-list) reversed-elements)  
               (done "The object is a long list (more than ~S elements).~%"))  
              ((consp in-list)  
               (push (cons (format nil "~D" length) (pop in-list))  
               (incf length))  
               (push (cons (string 'rest) in-list) reversed-elements)  
               (done "The object is an improper list of length ~S.~%")))))))  
1678  (defmethod inspected-parts ((o function))  (defmethod inspected-parts ((o function))
1679    (let ((header (kernel:get-type o)))    (let ((header (kernel:get-type o)))
1680      (cond ((= header vm:function-header-type)      (cond ((= header vm:function-header-type)
# Line 1304  nil if there's no second element." Line 1711  nil if there's no second element."
1711            `(("Name" . ,(kernel:fdefn-name o))            `(("Name" . ,(kernel:fdefn-name o))
1712              ("Function" . ,(kernel:fdefn-function o)))))              ("Function" . ,(kernel:fdefn-function o)))))
1714  ;;; Local Variables:  
1715  ;;; eval: (font-lock-add-keywords 'lisp-mode '(("(\\(defslimefun\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"  (1 font-lock-keyword-face) (2 font-lock-function-name-face))))  ;;;; Profiling
1716  ;;; End:  (defimplementation profile (fname)
1717      (eval `(profile:profile ,fname)))
1719    (defimplementation unprofile (fname)
1720      (eval `(profile:unprofile ,fname)))
1722    (defimplementation unprofile-all ()
1723      (profile:unprofile)
1724      "All functions unprofiled.")
1726    (defimplementation profile-report ()
1727      (profile:report-time))
1729    (defimplementation profile-reset ()
1730      (profile:reset-time)
1731      "Reset profiling counters.")
1733    (defimplementation profiled-functions ()
1734      profile:*timed-functions*)
1736    (defimplementation profile-package (package callers methods)
1737      (profile:profile-all :package package
1738                           :callers-p callers
1739                           #-cmu18e :methods #-cmu18e methods))
1742    ;;;; Multiprocessing
1744    #+mp
1745    (progn
1746      (defimplementation startup-multiprocessing ()
1747        ;; Threads magic: this never returns! But top-level becomes
1748        ;; available again.
1749        (mp::startup-idle-and-top-level-loops))
1751      (defimplementation spawn (fn &key (name "Anonymous"))
1752        (mp:make-process fn :name name))
1754      (defvar *thread-id-counter* 0)
1756      (defimplementation thread-id (thread)
1757        (or (getf (mp:process-property-list thread) 'id)
1758            (setf (getf (mp:process-property-list thread) 'id)
1759                  (incf *thread-id-counter*))))
1761      (defimplementation find-thread (id)
1762        (find id (all-threads)
1763              :key (lambda (p) (getf (mp:process-property-list p) 'id))))
1765      (defimplementation thread-name (thread)
1766        (mp:process-name thread))
1768      (defimplementation thread-status (thread)
1769        (mp:process-whostate thread))
1771      (defimplementation current-thread ()
1772        mp:*current-process*)
1774      (defimplementation all-threads ()
1775        (copy-list mp:*all-processes*))
1777      (defimplementation interrupt-thread (thread fn)
1778        (mp:process-interrupt thread fn))
1780      (defimplementation kill-thread (thread)
1781        (mp:destroy-process thread))
1783      (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
1785      (defstruct (mailbox (:conc-name mailbox.))
1786        (mutex (mp:make-lock "process mailbox"))
1787        (queue '() :type list))
1789      (defun mailbox (thread)
1790        "Return THREAD's mailbox."
1791        (mp:with-lock-held (*mailbox-lock*)
1792          (or (getf (mp:process-property-list thread) 'mailbox)
1793              (setf (getf (mp:process-property-list thread) 'mailbox)
1794                    (make-mailbox)))))
1796      (defimplementation send (thread message)
1797        (let* ((mbox (mailbox thread))
1798               (mutex (mailbox.mutex mbox)))
1799          (mp:with-lock-held (mutex)
1800            (setf (mailbox.queue mbox)
1801                  (nconc (mailbox.queue mbox) (list message))))))
1803      (defimplementation receive ()
1804        (let* ((mbox (mailbox mp:*current-process*))
1805               (mutex (mailbox.mutex mbox)))
1806          (mp:process-wait "receive" #'mailbox.queue mbox)
1807          (mp:with-lock-held (mutex)
1808            (pop (mailbox.queue mbox)))))
1810      ) ;; #+mp
1812    ;; Local Variables:
1813    ;; pbook-heading-regexp:    "^;;;\\(;+\\)"
1814    ;; pbook-commentary-regexp: "^;;;\\($\\|[^;]\\)"
1815    ;; End:

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

  ViewVC Help
Powered by ViewVC 1.1.5