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

Diff of /slime/swank-cmucl.lisp

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

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

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

  ViewVC Help
Powered by ViewVC 1.1.5