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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5