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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5