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

Contents of /slime/swank.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.362 - (show annotations)
Tue Feb 21 06:44:52 2006 UTC (8 years, 1 month ago) by mkoeppe
Branch: MAIN
Changes since 1.361: +58 -13 lines
(operator-designator-to-form): New, factored out from
arglist-for-echo-area.
(arglist-for-echo-area): Use it here.
(completions-for-keyword): New.
(find-matching-symbols-in-list): New.
1 ;;; -*- outline-regexp: ";;;;;*"; indent-tabs-mode: nil -*-
2 ;;;
3 ;;; This code has been placed in the Public Domain. All warranties
4 ;;; are disclaimed.
5 ;;;
6 ;;;; swank.lisp
7 ;;;
8 ;;; This file defines the "Swank" TCP server for Emacs to talk to. The
9 ;;; code in this file is purely portable Common Lisp. We do require a
10 ;;; smattering of non-portable functions in order to write the server,
11 ;;; so we have defined them in `swank-backend.lisp' and implemented
12 ;;; them separately for each Lisp implementation. These extensions are
13 ;;; available to us here via the `SWANK-BACKEND' package.
14
15 (defpackage :swank
16 (:use :common-lisp :swank-backend)
17 (:export #:startup-multiprocessing
18 #:start-server
19 #:create-swank-server
20 #:create-server
21 #:ed-in-emacs
22 #:print-indentation-lossage
23 #:swank-debugger-hook
24 ;; These are user-configurable variables:
25 #:*communication-style*
26 #:*log-events*
27 #:*log-output*
28 #:*use-dedicated-output-stream*
29 #:*dedicated-output-stream-port*
30 #:*configure-emacs-indentation*
31 #:*readtable-alist*
32 #:*globally-redirect-io*
33 #:*global-debugger*
34 #:*sldb-printer-bindings*
35 #:*swank-pprint-bindings*
36 #:*default-worker-thread-bindings*
37 #:*macroexpand-printer-bindings*
38 #:*record-repl-results*
39 ;; These are re-exported directly from the backend:
40 #:buffer-first-change
41 #:frame-source-location-for-emacs
42 #:restart-frame
43 #:sldb-step
44 #:sldb-break
45 #:sldb-break-on-return
46 #:profiled-functions
47 #:profile-report
48 #:profile-reset
49 #:unprofile-all
50 #:profile-package
51 #:default-directory
52 #:set-default-directory
53 #:quit-lisp))
54
55 (in-package :swank)
56
57
58 ;;;; Top-level variables, constants, macros
59
60 (defconstant cl-package (find-package :cl)
61 "The COMMON-LISP package.")
62
63 (defconstant keyword-package (find-package :keyword)
64 "The KEYWORD package.")
65
66 (defvar *canonical-package-nicknames*
67 `((:common-lisp-user . :cl-user))
68 "Canonical package names to use instead of shortest name/nickname.")
69
70 (defvar *auto-abbreviate-dotted-packages* t
71 "Abbreviate dotted package names to their last component if T.")
72
73 (defvar *swank-io-package*
74 (let ((package (make-package :swank-io-package :use '())))
75 (import '(nil t quote) package)
76 package))
77
78 (defconstant default-server-port 4005
79 "The default TCP port for the server (when started manually).")
80
81 (defvar *swank-debug-p* t
82 "When true, print extra debugging information.")
83
84 (defvar *redirect-io* t
85 "When non-nil redirect Lisp standard I/O to Emacs.
86 Redirection is done while Lisp is processing a request for Emacs.")
87
88 (defvar *sldb-printer-bindings*
89 `((*print-pretty* . nil)
90 (*print-level* . 4)
91 (*print-length* . 10)
92 (*print-circle* . t)
93 (*print-readably* . nil)
94 (*print-pprint-dispatch* . ,(copy-pprint-dispatch nil))
95 (*print-gensym* . t)
96 (*print-base* . 10)
97 (*print-radix* . nil)
98 (*print-array* . t)
99 (*print-lines* . 200)
100 (*print-escape* . t))
101 "A set of printer variables used in the debugger.")
102
103 (defvar *default-worker-thread-bindings* '()
104 "An alist to initialize dynamic variables in worker threads.
105 The list has the form ((VAR . VALUE) ...). Each variable VAR will be
106 bound to the corresponding VALUE.")
107
108 (defun call-with-bindings (alist fun)
109 "Call FUN with variables bound according to ALIST.
110 ALIST is a list of the form ((VAR . VAL) ...)."
111 (let* ((rlist (reverse alist))
112 (vars (mapcar #'car rlist))
113 (vals (mapcar #'cdr rlist)))
114 (progv vars vals
115 (funcall fun))))
116
117 (defmacro with-bindings (alist &body body)
118 "See `call-with-bindings'."
119 `(call-with-bindings ,alist (lambda () ,@body)))
120
121 ;;; The `DEFSLIMEFUN' macro defines a function that Emacs can call via
122 ;;; RPC.
123
124 (defmacro defslimefun (name arglist &body rest)
125 "A DEFUN for functions that Emacs can call by RPC."
126 `(progn
127 (defun ,name ,arglist ,@rest)
128 ;; see <http://www.franz.com/support/documentation/6.2/doc/pages/variables/compiler/s_cltl1-compile-file-toplevel-compatibility-p_s.htm>
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130 (export ',name :swank))))
131
132 (declaim (ftype (function () nil) missing-arg))
133 (defun missing-arg ()
134 "A function that the compiler knows will never to return a value.
135 You can use (MISSING-ARG) as the initform for defstruct slots that
136 must always be supplied. This way the :TYPE slot option need not
137 include some arbitrary initial value like NIL."
138 (error "A required &KEY or &OPTIONAL argument was not supplied."))
139
140
141 ;;;; Hooks
142 ;;;
143 ;;; We use Emacs-like `add-hook' and `run-hook' utilities to support
144 ;;; simple indirection. The interface is more CLish than the Emacs
145 ;;; Lisp one.
146
147 (defmacro add-hook (place function)
148 "Add FUNCTION to the list of values on PLACE."
149 `(pushnew ,function ,place))
150
151 (defun run-hook (functions &rest arguments)
152 "Call each of FUNCTIONS with ARGUMENTS."
153 (dolist (function functions)
154 (apply function arguments)))
155
156 (defvar *new-connection-hook* '()
157 "This hook is run each time a connection is established.
158 The connection structure is given as the argument.
159 Backend code should treat the connection structure as opaque.")
160
161 (defvar *connection-closed-hook* '()
162 "This hook is run when a connection is closed.
163 The connection as passed as an argument.
164 Backend code should treat the connection structure as opaque.")
165
166 (defvar *pre-reply-hook* '()
167 "Hook run (without arguments) immediately before replying to an RPC.")
168
169
170 ;;;; Connections
171 ;;;
172 ;;; Connection structures represent the network connections between
173 ;;; Emacs and Lisp. Each has a socket stream, a set of user I/O
174 ;;; streams that redirect to Emacs, and optionally a second socket
175 ;;; used solely to pipe user-output to Emacs (an optimization).
176 ;;;
177
178 (defvar *coding-system* ':iso-latin-1-unix)
179
180 (defstruct (connection
181 (:conc-name connection.)
182 (:print-function print-connection))
183 ;; Raw I/O stream of socket connection.
184 (socket-io (missing-arg) :type stream :read-only t)
185 ;; Optional dedicated output socket (backending `user-output' slot).
186 ;; Has a slot so that it can be closed with the connection.
187 (dedicated-output nil :type (or stream null))
188 ;; Streams that can be used for user interaction, with requests
189 ;; redirected to Emacs.
190 (user-input nil :type (or stream null))
191 (user-output nil :type (or stream null))
192 (user-io nil :type (or stream null))
193 ;; In multithreaded systems we delegate certain tasks to specific
194 ;; threads. The `reader-thread' is responsible for reading network
195 ;; requests from Emacs and sending them to the `control-thread'; the
196 ;; `control-thread' is responsible for dispatching requests to the
197 ;; threads that should handle them; the `repl-thread' is the one
198 ;; that evaluates REPL expressions. The control thread dispatches
199 ;; all REPL evaluations to the REPL thread and for other requests it
200 ;; spawns new threads.
201 reader-thread
202 control-thread
203 repl-thread
204 ;; Callback functions:
205 ;; (SERVE-REQUESTS <this-connection>) serves all pending requests
206 ;; from Emacs.
207 (serve-requests (missing-arg) :type function)
208 ;; (READ) is called to read and return one message from Emacs.
209 (read (missing-arg) :type function)
210 ;; (SEND OBJECT) is called to send one message to Emacs.
211 (send (missing-arg) :type function)
212 ;; (CLEANUP <this-connection>) is called when the connection is
213 ;; closed.
214 (cleanup nil :type (or null function))
215 ;; Cache of macro-indentation information that has been sent to Emacs.
216 ;; This is used for preparing deltas to update Emacs's knowledge.
217 ;; Maps: symbol -> indentation-specification
218 (indentation-cache (make-hash-table :test 'eq) :type hash-table)
219 ;; The list of packages represented in the cache:
220 (indentation-cache-packages '())
221 ;; The communication style used.
222 (communication-style nil :type (member nil :spawn :sigio :fd-handler))
223 ;; The coding system for network streams.
224 (external-format *coding-system* :type (member :iso-latin-1-unix
225 :emacs-mule-unix
226 :utf-8-unix
227 :euc-jp-unix)))
228
229 (defun print-connection (conn stream depth)
230 (declare (ignore depth))
231 (print-unreadable-object (conn stream :type t :identity t)))
232
233 (defvar *connections* '()
234 "List of all active connections, with the most recent at the front.")
235
236 (defvar *emacs-connection* nil
237 "The connection to Emacs currently in use.")
238
239 (defvar *swank-state-stack* '()
240 "A list of symbols describing the current state. Used for debugging
241 and to detect situations where interrupts can be ignored.")
242
243 (defun default-connection ()
244 "Return the 'default' Emacs connection.
245 This connection can be used to talk with Emacs when no specific
246 connection is in use, i.e. *EMACS-CONNECTION* is NIL.
247
248 The default connection is defined (quite arbitrarily) as the most
249 recently established one."
250 (first *connections*))
251
252 (defslimefun state-stack ()
253 "Return the value of *SWANK-STATE-STACK*."
254 *swank-state-stack*)
255
256 (define-condition slime-protocol-error (error)
257 ((condition :initarg :condition :reader slime-protocol-error.condition))
258 (:report (lambda (condition stream)
259 (format stream "~A" (slime-protocol-error.condition condition)))))
260
261 (add-hook *new-connection-hook* 'notify-backend-of-connection)
262 (defun notify-backend-of-connection (connection)
263 (declare (ignore connection))
264 (emacs-connected))
265
266
267 ;;;; Helper macros
268
269 (defmacro with-io-redirection ((connection) &body body)
270 "Execute BODY I/O redirection to CONNECTION.
271 If *REDIRECT-IO* is true then all standard I/O streams are redirected."
272 `(maybe-call-with-io-redirection ,connection (lambda () ,@body)))
273
274 (defun maybe-call-with-io-redirection (connection fun)
275 (if *redirect-io*
276 (call-with-redirected-io connection fun)
277 (funcall fun)))
278
279 (defmacro with-connection ((connection) &body body)
280 "Execute BODY in the context of CONNECTION."
281 `(call-with-connection ,connection (lambda () ,@body)))
282
283 (defun call-with-connection (connection fun)
284 (let ((*emacs-connection* connection))
285 (with-io-redirection (*emacs-connection*)
286 (call-with-debugger-hook #'swank-debugger-hook fun))))
287
288 (defmacro without-interrupts (&body body)
289 `(call-without-interrupts (lambda () ,@body)))
290
291 (defmacro destructure-case (value &rest patterns)
292 "Dispatch VALUE to one of PATTERNS.
293 A cross between `case' and `destructuring-bind'.
294 The pattern syntax is:
295 ((HEAD . ARGS) . BODY)
296 The list of patterns is searched for a HEAD `eq' to the car of
297 VALUE. If one is found, the BODY is executed with ARGS bound to the
298 corresponding values in the CDR of VALUE."
299 (let ((operator (gensym "op-"))
300 (operands (gensym "rand-"))
301 (tmp (gensym "tmp-")))
302 `(let* ((,tmp ,value)
303 (,operator (car ,tmp))
304 (,operands (cdr ,tmp)))
305 (case ,operator
306 ,@(loop for (pattern . body) in patterns collect
307 (if (eq pattern t)
308 `(t ,@body)
309 (destructuring-bind (op &rest rands) pattern
310 `(,op (destructuring-bind ,rands ,operands
311 ,@body)))))
312 ,@(if (eq (caar (last patterns)) t)
313 '()
314 `((t (error "destructure-case failed: ~S" ,tmp))))))))
315
316 (defmacro with-temp-package (var &body body)
317 "Execute BODY with VAR bound to a temporary package.
318 The package is deleted before returning."
319 `(let ((,var (make-package (gensym "TEMP-PACKAGE-"))))
320 (unwind-protect (progn ,@body)
321 (delete-package ,var))))
322
323 (defvar *log-events* nil)
324 (defvar *log-output* *error-output*)
325 (defvar *event-history* (make-array 40 :initial-element nil)
326 "A ring buffer to record events for better error messages.")
327 (defvar *event-history-index* 0)
328 (defvar *enable-event-history* t)
329
330 (defun log-event (format-string &rest args)
331 "Write a message to *terminal-io* when *log-events* is non-nil.
332 Useful for low level debugging."
333 (when *enable-event-history*
334 (setf (aref *event-history* *event-history-index*)
335 (format nil "~?" format-string args))
336 (setf *event-history-index*
337 (mod (1+ *event-history-index*) (length *event-history*))))
338 (when *log-events*
339 (apply #'format *log-output* format-string args)
340 (force-output *log-output*)))
341
342 (defun event-history-to-list ()
343 "Return the list of events (older events first)."
344 (let ((arr *event-history*)
345 (idx *event-history-index*))
346 (concatenate 'list (subseq arr idx) (subseq arr 0 idx))))
347
348 (defun dump-event-history (stream)
349 (dolist (e (event-history-to-list))
350 (dump-event e stream)))
351
352 (defun dump-event (event stream)
353 (cond ((stringp event)
354 (write-string (escape-non-ascii event) stream))
355 ((null event))
356 (t (format stream "Unexpected event: ~A~%" event))))
357
358 (defun escape-non-ascii (string)
359 "Return a string like STRING but with non-ascii chars escaped."
360 (cond ((ascii-string-p string) string)
361 (t (with-output-to-string (out)
362 (loop for c across string do
363 (cond ((ascii-char-p c) (write-char c out))
364 (t (format out "\\x~4,'0X" (char-code c)))))))))
365
366 (defun ascii-string-p (o)
367 (and (stringp o)
368 (every #'ascii-char-p o)))
369
370 (defun ascii-char-p (c)
371 (<= (char-code c) 127))
372
373
374 ;;;; TCP Server
375
376 (defvar *use-dedicated-output-stream* t
377 "When T swank will attempt to create a second connection to
378 Emacs which is used just to send output.")
379
380 (defvar *dedicated-output-stream-port* 0
381 "Which port we should use for the dedicated output stream.")
382
383 (defvar *communication-style* (preferred-communication-style))
384
385 (defvar *dedicated-output-stream-buffering*
386 (if (eq *communication-style* :spawn) :full :none)
387 "The buffering scheme that should be used for the output stream.
388 Valid values are :none, :line, and :full.")
389
390 (defun start-server (port-file &key (style *communication-style*)
391 dont-close (external-format *coding-system*))
392 "Start the server and write the listen port number to PORT-FILE.
393 This is the entry point for Emacs."
394 (when (eq style :spawn)
395 (initialize-multiprocessing))
396 (setup-server 0 (lambda (port) (announce-server-port port-file port))
397 style dont-close external-format)
398 (when (eq style :spawn)
399 (startup-idle-and-top-level-loops)))
400
401 (defun create-server (&key (port default-server-port)
402 (style *communication-style*)
403 dont-close (external-format *coding-system*))
404 "Start a SWANK server on PORT running in STYLE.
405 If DONT-CLOSE is true then the listen socket will accept multiple
406 connections, otherwise it will be closed after the first."
407 (setup-server port #'simple-announce-function style dont-close
408 external-format))
409
410 (defun create-swank-server (&optional (port default-server-port)
411 (style *communication-style*)
412 (announce-fn #'simple-announce-function)
413 dont-close (external-format *coding-system*))
414 (setup-server port announce-fn style dont-close external-format))
415
416 (defparameter *loopback-interface* "127.0.0.1")
417
418 (defun setup-server (port announce-fn style dont-close external-format)
419 (declare (type function announce-fn))
420 (let* ((socket (create-socket *loopback-interface* port))
421 (port (local-port socket)))
422 (funcall announce-fn port)
423 (flet ((serve ()
424 (serve-connection socket style dont-close external-format)))
425 (ecase style
426 (:spawn
427 (spawn (lambda () (loop do (serve) while dont-close))
428 :name "Swank"))
429 ((:fd-handler :sigio)
430 (add-fd-handler socket (lambda () (serve))))
431 ((nil) (loop do (serve) while dont-close)))
432 port)))
433
434 (defun serve-connection (socket style dont-close external-format)
435 (let ((client (accept-authenticated-connection
436 socket :external-format external-format)))
437 (unless dont-close
438 (close-socket socket))
439 (let ((connection (create-connection client style external-format)))
440 (run-hook *new-connection-hook* connection)
441 (push connection *connections*)
442 (serve-requests connection))))
443
444 (defun accept-authenticated-connection (&rest args)
445 (let ((new (apply #'accept-connection args))
446 (secret (slime-secret)))
447 (when secret
448 (let ((first-val (decode-message new)))
449 (unless (and (stringp first-val) (string= first-val secret))
450 (close new)
451 (error "Incoming connection doesn't know the password."))))
452 new))
453
454 (defun slime-secret ()
455 "Finds the magic secret from the user's home directory. Returns nil
456 if the file doesn't exist; otherwise the first line of the file."
457 (with-open-file (in
458 (merge-pathnames (user-homedir-pathname) #p".slime-secret")
459 :if-does-not-exist nil)
460 (and in (read-line in nil ""))))
461
462 (defun serve-requests (connection)
463 "Read and process all requests on connections."
464 (funcall (connection.serve-requests connection) connection))
465
466 (defun announce-server-port (file port)
467 (with-open-file (s file
468 :direction :output
469 :if-exists :error
470 :if-does-not-exist :create)
471 (format s "~S~%" port))
472 (simple-announce-function port))
473
474 (defun simple-announce-function (port)
475 (when *swank-debug-p*
476 (format *debug-io* "~&;; Swank started at port: ~D.~%" port)
477 (force-output *debug-io*)))
478
479 (defun open-streams (connection)
480 "Return the 4 streams for IO redirection:
481 DEDICATED-OUTPUT INPUT OUTPUT IO"
482 (multiple-value-bind (output-fn dedicated-output)
483 (make-output-function connection)
484 (let ((input-fn
485 (lambda ()
486 (with-connection (connection)
487 (with-simple-restart (abort-read
488 "Abort reading input from Emacs.")
489 (read-user-input-from-emacs))))))
490 (multiple-value-bind (in out) (make-fn-streams input-fn output-fn)
491 (let ((out (or dedicated-output out)))
492 (let ((io (make-two-way-stream in out)))
493 (mapc #'make-stream-interactive (list in out io))
494 (values dedicated-output in out io)))))))
495
496 (defun make-output-function (connection)
497 "Create function to send user output to Emacs.
498 This function may open a dedicated socket to send output. It
499 returns two values: the output function, and the dedicated
500 stream (or NIL if none was created)."
501 (if *use-dedicated-output-stream*
502 (let ((stream (open-dedicated-output-stream
503 (connection.socket-io connection)
504 (connection.external-format connection))))
505 (values (lambda (string)
506 (write-string string stream)
507 (force-output stream))
508 stream))
509 (values (lambda (string)
510 (with-connection (connection)
511 (with-simple-restart
512 (abort "Abort sending output to Emacs.")
513 (send-to-emacs `(:write-string ,string)))))
514 nil)))
515
516 (defun open-dedicated-output-stream (socket-io external-format)
517 "Open a dedicated output connection to the Emacs on SOCKET-IO.
518 Return an output stream suitable for writing program output.
519
520 This is an optimized way for Lisp to deliver output to Emacs."
521 (let* ((socket (create-socket *loopback-interface*
522 *dedicated-output-stream-port*))
523 (port (local-port socket)))
524 (encode-message `(:open-dedicated-output-stream ,port) socket-io)
525 (accept-authenticated-connection
526 socket :external-format external-format
527 :buffering *dedicated-output-stream-buffering*)))
528
529 (defun handle-request (connection)
530 "Read and process one request. The processing is done in the extend
531 of the toplevel restart."
532 (assert (null *swank-state-stack*))
533 (let ((*swank-state-stack* '(:handle-request)))
534 (with-connection (connection)
535 (with-simple-restart (abort-request "Abort handling SLIME request.")
536 (read-from-emacs)))))
537
538 (defun current-socket-io ()
539 (connection.socket-io *emacs-connection*))
540
541 (defun close-connection (c &optional condition)
542 (let ((cleanup (connection.cleanup c)))
543 (when cleanup
544 (funcall cleanup c)))
545 (close (connection.socket-io c))
546 (when (connection.dedicated-output c)
547 (close (connection.dedicated-output c)))
548 (setf *connections* (remove c *connections*))
549 (run-hook *connection-closed-hook* c)
550 (when condition
551 (finish-output *debug-io*)
552 (format *debug-io* "~&;; Event history start:~%")
553 (dump-event-history *debug-io*)
554 (format *debug-io* ";; Event history end.~%~
555 ;; Connection to Emacs lost. [~%~
556 ;; condition: ~A~%~
557 ;; type: ~S~%~
558 ;; encoding: ~S style: ~S dedicated: ~S]~%"
559 (escape-non-ascii (safe-condition-message condition) )
560 (type-of condition)
561 (connection.external-format c)
562 (connection.communication-style c)
563 *use-dedicated-output-stream*)
564 (finish-output *debug-io*)))
565
566 (defmacro with-reader-error-handler ((connection) &body body)
567 `(handler-case (progn ,@body)
568 (slime-protocol-error (e)
569 (close-connection ,connection e))))
570
571 (defslimefun simple-break ()
572 (with-simple-restart (continue "Continue from interrupt.")
573 (call-with-debugger-hook
574 #'swank-debugger-hook
575 (lambda ()
576 (invoke-debugger
577 (make-condition 'simple-error
578 :format-control "Interrupt from Emacs")))))
579 nil)
580
581 ;;;;;; Thread based communication
582
583 (defvar *active-threads* '())
584
585 (defun read-loop (control-thread input-stream connection)
586 (with-reader-error-handler (connection)
587 (loop (send control-thread (decode-message input-stream)))))
588
589 (defun dispatch-loop (socket-io connection)
590 (let ((*emacs-connection* connection))
591 (handler-case
592 (loop (dispatch-event (receive) socket-io))
593 (error (e)
594 (close-connection connection e)))))
595
596 (defun repl-thread (connection)
597 (let ((thread (connection.repl-thread connection)))
598 (when (not thread)
599 (log-event "ERROR: repl-thread is nil"))
600 (assert thread)
601 (cond ((thread-alive-p thread)
602 thread)
603 (t
604 (setf (connection.repl-thread connection)
605 (spawn-repl-thread connection "new-repl-thread"))))))
606
607 (defun find-worker-thread (id)
608 (etypecase id
609 ((member t)
610 (car *active-threads*))
611 ((member :repl-thread)
612 (repl-thread *emacs-connection*))
613 (fixnum
614 (find-thread id))))
615
616 (defun interrupt-worker-thread (id)
617 (let ((thread (or (find-worker-thread id)
618 (repl-thread *emacs-connection*))))
619 (interrupt-thread thread #'simple-break)))
620
621 (defun thread-for-evaluation (id)
622 "Find or create a thread to evaluate the next request."
623 (let ((c *emacs-connection*))
624 (etypecase id
625 ((member t)
626 (spawn-worker-thread c))
627 ((member :repl-thread)
628 (repl-thread c))
629 (fixnum
630 (find-thread id)))))
631
632 (defun spawn-worker-thread (connection)
633 (spawn (lambda ()
634 (with-bindings *default-worker-thread-bindings*
635 (handle-request connection)))
636 :name "worker"))
637
638 (defun spawn-repl-thread (connection name)
639 (spawn (lambda ()
640 (with-bindings *default-worker-thread-bindings*
641 (repl-loop connection)))
642 :name name))
643
644 (defun dispatch-event (event socket-io)
645 "Handle an event triggered either by Emacs or within Lisp."
646 (log-event "DISPATCHING: ~S~%" event)
647 (destructure-case event
648 ((:emacs-rex form package thread-id id)
649 (let ((thread (thread-for-evaluation thread-id)))
650 (push thread *active-threads*)
651 (send thread `(eval-for-emacs ,form ,package ,id))))
652 ((:return thread &rest args)
653 (let ((tail (member thread *active-threads*)))
654 (setq *active-threads* (nconc (ldiff *active-threads* tail)
655 (cdr tail))))
656 (encode-message `(:return ,@args) socket-io))
657 ((:emacs-interrupt thread-id)
658 (interrupt-worker-thread thread-id))
659 (((:debug :debug-condition :debug-activate :debug-return)
660 thread &rest args)
661 (encode-message `(,(car event) ,(thread-id thread) ,@args) socket-io))
662 ((:read-string thread &rest args)
663 (encode-message `(:read-string ,(thread-id thread) ,@args) socket-io))
664 ((:y-or-n-p thread &rest args)
665 (encode-message `(:y-or-n-p ,(thread-id thread) ,@args) socket-io))
666 ((:read-aborted thread &rest args)
667 (encode-message `(:read-aborted ,(thread-id thread) ,@args) socket-io))
668 ((:emacs-return-string thread-id tag string)
669 (send (find-thread thread-id) `(take-input ,tag ,string)))
670 ((:eval thread &rest args)
671 (encode-message `(:eval ,(thread-id thread) ,@args) socket-io))
672 ((:emacs-return thread-id tag value)
673 (send (find-thread thread-id) `(take-input ,tag ,value)))
674 (((:write-string :presentation-start :presentation-end
675 :new-package :new-features :ed :%apply :indentation-update
676 :eval-no-wait :background-message)
677 &rest _)
678 (declare (ignore _))
679 (encode-message event socket-io))))
680
681 (defun spawn-threads-for-connection (connection)
682 (macrolet ((without-debugger-hook (&body body)
683 `(call-with-debugger-hook nil (lambda () ,@body))))
684 (let* ((socket-io (connection.socket-io connection))
685 (control-thread (spawn (lambda ()
686 (without-debugger-hook
687 (dispatch-loop socket-io connection)))
688 :name "control-thread")))
689 (setf (connection.control-thread connection) control-thread)
690 (let ((reader-thread (spawn (lambda ()
691 (let ((go (receive)))
692 (assert (eq go 'accept-input)))
693 (without-debugger-hook
694 (read-loop control-thread socket-io
695 connection)))
696 :name "reader-thread"))
697 (repl-thread (spawn-repl-thread connection "repl-thread")))
698 (setf (connection.repl-thread connection) repl-thread)
699 (setf (connection.reader-thread connection) reader-thread)
700 (send reader-thread 'accept-input)
701 connection))))
702
703 (defun cleanup-connection-threads (connection)
704 (let ((threads (list (connection.repl-thread connection)
705 (connection.reader-thread connection)
706 (connection.control-thread connection))))
707 (dolist (thread threads)
708 (when (and thread
709 (thread-alive-p thread)
710 (not (equal (current-thread) thread)))
711 (kill-thread thread)))))
712
713 (defun repl-loop (connection)
714 (with-connection (connection)
715 (loop (handle-request connection))))
716
717 (defun process-available-input (stream fn)
718 (loop while (and (open-stream-p stream)
719 (listen stream))
720 do (funcall fn)))
721
722 ;;;;;; Signal driven IO
723
724 (defun install-sigio-handler (connection)
725 (let ((client (connection.socket-io connection)))
726 (flet ((handler ()
727 (cond ((null *swank-state-stack*)
728 (with-reader-error-handler (connection)
729 (process-available-input
730 client (lambda () (handle-request connection)))))
731 ((eq (car *swank-state-stack*) :read-next-form))
732 (t (process-available-input client #'read-from-emacs)))))
733 (add-sigio-handler client #'handler)
734 (handler))))
735
736 (defun deinstall-sigio-handler (connection)
737 (remove-sigio-handlers (connection.socket-io connection)))
738
739 ;;;;;; SERVE-EVENT based IO
740
741 (defun install-fd-handler (connection)
742 (let ((client (connection.socket-io connection)))
743 (flet ((handler ()
744 (cond ((null *swank-state-stack*)
745 (with-reader-error-handler (connection)
746 (process-available-input
747 client (lambda () (handle-request connection)))))
748 ((eq (car *swank-state-stack*) :read-next-form))
749 (t
750 (process-available-input client #'read-from-emacs)))))
751 ;; handle sigint
752 (install-debugger-globally
753 (lambda (c h)
754 (with-reader-error-handler (connection)
755 (block debugger
756 (with-connection (connection)
757 (swank-debugger-hook c h)
758 (return-from debugger))
759 (abort)))))
760 (add-fd-handler client #'handler)
761 (handler))))
762
763 (defun deinstall-fd-handler (connection)
764 (remove-fd-handlers (connection.socket-io connection)))
765
766 ;;;;;; Simple sequential IO
767
768 (defun simple-serve-requests (connection)
769 (with-reader-error-handler (connection)
770 (unwind-protect
771 (loop
772 (with-connection (connection)
773 (with-simple-restart (abort-request "")
774 (do ()
775 ((wait-until-readable (connection.socket-io connection))))))
776 (handle-request connection))
777 (close-connection connection))))
778
779 (defun wait-until-readable (stream)
780 (unread-char (read-char stream) stream)
781 t)
782
783 (defun read-from-socket-io ()
784 (let ((event (decode-message (current-socket-io))))
785 (log-event "DISPATCHING: ~S~%" event)
786 (destructure-case event
787 ((:emacs-rex form package thread id)
788 (declare (ignore thread))
789 `(eval-for-emacs ,form ,package ,id))
790 ((:emacs-interrupt thread)
791 (declare (ignore thread))
792 '(simple-break))
793 ((:emacs-return-string thread tag string)
794 (declare (ignore thread))
795 `(take-input ,tag ,string))
796 ((:emacs-return thread tag value)
797 (declare (ignore thread))
798 `(take-input ,tag ,value)))))
799
800 (defun send-to-socket-io (event)
801 (log-event "DISPATCHING: ~S~%" event)
802 (flet ((send (o)
803 (without-interrupts
804 (encode-message o (current-socket-io)))))
805 (destructure-case event
806 (((:debug-activate :debug :debug-return :read-string :read-aborted
807 :y-or-n-p :eval)
808 thread &rest args)
809 (declare (ignore thread))
810 (send `(,(car event) 0 ,@args)))
811 ((:return thread &rest args)
812 (declare (ignore thread))
813 (send `(:return ,@args)))
814 (((:write-string :new-package :new-features :debug-condition
815 :presentation-start :presentation-end
816 :indentation-update :ed :%apply :eval-no-wait
817 :background-message)
818 &rest _)
819 (declare (ignore _))
820 (send event)))))
821
822 (defun initialize-streams-for-connection (connection)
823 (multiple-value-bind (dedicated in out io) (open-streams connection)
824 (setf (connection.dedicated-output connection) dedicated
825 (connection.user-io connection) io
826 (connection.user-output connection) out
827 (connection.user-input connection) in)
828 connection))
829
830 (defun create-connection (socket-io style external-format)
831 (let ((c (ecase style
832 (:spawn
833 (make-connection :socket-io socket-io
834 :read #'read-from-control-thread
835 :send #'send-to-control-thread
836 :serve-requests #'spawn-threads-for-connection
837 :cleanup #'cleanup-connection-threads))
838 (:sigio
839 (make-connection :socket-io socket-io
840 :read #'read-from-socket-io
841 :send #'send-to-socket-io
842 :serve-requests #'install-sigio-handler
843 :cleanup #'deinstall-sigio-handler))
844 (:fd-handler
845 (make-connection :socket-io socket-io
846 :read #'read-from-socket-io
847 :send #'send-to-socket-io
848 :serve-requests #'install-fd-handler
849 :cleanup #'deinstall-fd-handler))
850 ((nil)
851 (make-connection :socket-io socket-io
852 :read #'read-from-socket-io
853 :send #'send-to-socket-io
854 :serve-requests #'simple-serve-requests)))))
855 (setf (connection.communication-style c) style)
856 (setf (connection.external-format c) external-format)
857 (initialize-streams-for-connection c)
858 c))
859
860
861 ;;;; IO to Emacs
862 ;;;
863 ;;; This code handles redirection of the standard I/O streams
864 ;;; (`*standard-output*', etc) into Emacs. The `connection' structure
865 ;;; contains the appropriate streams, so all we have to do is make the
866 ;;; right bindings.
867
868 ;;;;; Global I/O redirection framework
869 ;;;
870 ;;; Optionally, the top-level global bindings of the standard streams
871 ;;; can be assigned to be redirected to Emacs. When Emacs connects we
872 ;;; redirect the streams into the connection, and they keep going into
873 ;;; that connection even if more are established. If the connection
874 ;;; handling the streams closes then another is chosen, or if there
875 ;;; are no connections then we revert to the original (real) streams.
876 ;;;
877 ;;; It is slightly tricky to assign the global values of standard
878 ;;; streams because they are often shadowed by dynamic bindings. We
879 ;;; solve this problem by introducing an extra indirection via synonym
880 ;;; streams, so that *STANDARD-INPUT* is a synonym stream to
881 ;;; *CURRENT-STANDARD-INPUT*, etc. We never shadow the "current"
882 ;;; variables, so they can always be assigned to affect a global
883 ;;; change.
884
885 (defvar *globally-redirect-io* nil
886 "When non-nil globally redirect all standard streams to Emacs.")
887
888 (defmacro setup-stream-indirection (stream-var)
889 "Setup redirection scaffolding for a global stream variable.
890 Supposing (for example) STREAM-VAR is *STANDARD-INPUT*, this macro:
891
892 1. Saves the value of *STANDARD-INPUT* in a variable called
893 *REAL-STANDARD-INPUT*.
894
895 2. Creates *CURRENT-STANDARD-INPUT*, initially with the same value as
896 *STANDARD-INPUT*.
897
898 3. Assigns *STANDARD-INPUT* to a synonym stream pointing to
899 *CURRENT-STANDARD-INPUT*.
900
901 This has the effect of making *CURRENT-STANDARD-INPUT* contain the
902 effective global value for *STANDARD-INPUT*. This way we can assign
903 the effective global value even when *STANDARD-INPUT* is shadowed by a
904 dynamic binding."
905 (let ((real-stream-var (prefixed-var "REAL" stream-var))
906 (current-stream-var (prefixed-var "CURRENT" stream-var)))
907 `(progn
908 ;; Save the real stream value for the future.
909 (defvar ,real-stream-var ,stream-var)
910 ;; Define a new variable for the effective stream.
911 ;; This can be reassigned.
912 (defvar ,current-stream-var ,stream-var)
913 ;; Assign the real binding as a synonym for the current one.
914 (setq ,stream-var (make-synonym-stream ',current-stream-var)))))
915
916 (eval-when (:compile-toplevel :load-toplevel :execute)
917 (defun prefixed-var (prefix variable-symbol)
918 "(PREFIXED-VAR \"FOO\" '*BAR*) => SWANK::*FOO-BAR*"
919 (let ((basename (subseq (symbol-name variable-symbol) 1)))
920 (intern (format nil "*~A-~A" prefix basename) :swank))))
921
922 ;;;;; Global redirection setup
923
924 (setup-stream-indirection *standard-output*)
925 (setup-stream-indirection *error-output*)
926 (setup-stream-indirection *trace-output*)
927 (setup-stream-indirection *standard-input*)
928 (setup-stream-indirection *debug-io*)
929 (setup-stream-indirection *query-io*)
930 (setup-stream-indirection *terminal-io*)
931
932 (defparameter *standard-output-streams*
933 '(*standard-output* *error-output* *trace-output*)
934 "The symbols naming standard output streams.")
935
936 (defparameter *standard-input-streams*
937 '(*standard-input*)
938 "The symbols naming standard input streams.")
939
940 (defparameter *standard-io-streams*
941 '(*debug-io* *query-io* *terminal-io*)
942 "The symbols naming standard io streams.")
943
944 (defun globally-redirect-io-to-connection (connection)
945 "Set the standard I/O streams to redirect to CONNECTION.
946 Assigns *CURRENT-<STREAM>* for all standard streams."
947 (dolist (o *standard-output-streams*)
948 (set (prefixed-var "CURRENT" o)
949 (connection.user-output connection)))
950 ;; FIXME: If we redirect standard input to Emacs then we get the
951 ;; regular Lisp top-level trying to read from our REPL.
952 ;;
953 ;; Perhaps the ideal would be for the real top-level to run in a
954 ;; thread with local bindings for all the standard streams. Failing
955 ;; that we probably would like to inhibit it from reading while
956 ;; Emacs is connected.
957 ;;
958 ;; Meanwhile we just leave *standard-input* alone.
959 #+NIL
960 (dolist (i *standard-input-streams*)
961 (set (prefixed-var "CURRENT" i)
962 (connection.user-input connection)))
963 (dolist (io *standard-io-streams*)
964 (set (prefixed-var "CURRENT" io)
965 (connection.user-io connection))))
966
967 (defun revert-global-io-redirection ()
968 "Set *CURRENT-<STREAM>* to *REAL-<STREAM>* for all standard streams."
969 (dolist (stream-var (append *standard-output-streams*
970 *standard-input-streams*
971 *standard-io-streams*))
972 (set (prefixed-var "CURRENT" stream-var)
973 (symbol-value (prefixed-var "REAL" stream-var)))))
974
975 ;;;;; Global redirection hooks
976
977 (defvar *global-stdio-connection* nil
978 "The connection to which standard I/O streams are globally redirected.
979 NIL if streams are not globally redirected.")
980
981 (defun maybe-redirect-global-io (connection)
982 "Consider globally redirecting to a newly-established CONNECTION."
983 (when (and *globally-redirect-io* (null *global-stdio-connection*))
984 (setq *global-stdio-connection* connection)
985 (globally-redirect-io-to-connection connection)))
986
987 (defun update-redirection-after-close (closed-connection)
988 "Update redirection after a connection closes."
989 (when (eq *global-stdio-connection* closed-connection)
990 (if (and (default-connection) *globally-redirect-io*)
991 ;; Redirect to another connection.
992 (globally-redirect-io-to-connection (default-connection))
993 ;; No more connections, revert to the real streams.
994 (progn (revert-global-io-redirection)
995 (setq *global-stdio-connection* nil)))))
996
997 (add-hook *new-connection-hook* 'maybe-redirect-global-io)
998 (add-hook *connection-closed-hook* 'update-redirection-after-close)
999
1000 ;;;;; Redirection during requests
1001 ;;;
1002 ;;; We always redirect the standard streams to Emacs while evaluating
1003 ;;; an RPC. This is done with simple dynamic bindings.
1004
1005 (defun call-with-redirected-io (connection function)
1006 "Call FUNCTION with I/O streams redirected via CONNECTION."
1007 (declare (type function function))
1008 (let* ((io (connection.user-io connection))
1009 (in (connection.user-input connection))
1010 (out (connection.user-output connection))
1011 (*standard-output* out)
1012 (*error-output* out)
1013 (*trace-output* out)
1014 (*debug-io* io)
1015 (*query-io* io)
1016 (*standard-input* in)
1017 (*terminal-io* io))
1018 (funcall function)))
1019
1020 (defun read-from-emacs ()
1021 "Read and process a request from Emacs."
1022 (apply #'funcall (funcall (connection.read *emacs-connection*))))
1023
1024 (defun read-from-control-thread ()
1025 (receive))
1026
1027 (defun decode-message (stream)
1028 "Read an S-expression from STREAM using the SLIME protocol.
1029 If a protocol error occurs then a SLIME-PROTOCOL-ERROR is signalled."
1030 (let ((*swank-state-stack* (cons :read-next-form *swank-state-stack*)))
1031 (handler-case
1032 (let* ((length (decode-message-length stream))
1033 (string (make-string length))
1034 (pos (read-sequence string stream)))
1035 (assert (= pos length) ()
1036 "Short read: length=~D pos=~D" length pos)
1037 (log-event "READ: ~S~%" string)
1038 (read-form string))
1039 (serious-condition (c)
1040 (error (make-condition 'slime-protocol-error :condition c))))))
1041
1042 (defun decode-message-length (stream)
1043 (let ((buffer (make-string 6)))
1044 (dotimes (i 6)
1045 (setf (aref buffer i) (read-char stream)))
1046 (parse-integer buffer :radix #x10)))
1047
1048 (defun read-form (string)
1049 (with-standard-io-syntax
1050 (let ((*package* *swank-io-package*))
1051 (read-from-string string))))
1052
1053 (defvar *slime-features* nil
1054 "The feature list that has been sent to Emacs.")
1055
1056 (defun send-to-emacs (object)
1057 "Send OBJECT to Emacs."
1058 (funcall (connection.send *emacs-connection*) object))
1059
1060 (defun send-oob-to-emacs (object)
1061 (send-to-emacs object))
1062
1063 (defun send-to-control-thread (object)
1064 (send (connection.control-thread *emacs-connection*) object))
1065
1066 (defun encode-message (message stream)
1067 (let* ((string (prin1-to-string-for-emacs message))
1068 (length (length string)))
1069 (log-event "WRITE: ~A~%" string)
1070 (let ((*print-pretty* nil))
1071 (format stream "~6,'0x" length))
1072 (write-string string stream)
1073 ;;(terpri stream)
1074 (finish-output stream)))
1075
1076 (defun prin1-to-string-for-emacs (object)
1077 (with-standard-io-syntax
1078 (let ((*print-case* :downcase)
1079 (*print-readably* nil)
1080 (*print-pretty* nil)
1081 (*package* *swank-io-package*))
1082 (prin1-to-string object))))
1083
1084 (defun force-user-output ()
1085 (force-output (connection.user-io *emacs-connection*))
1086 (finish-output (connection.user-output *emacs-connection*)))
1087
1088 (defun clear-user-input ()
1089 (clear-input (connection.user-input *emacs-connection*)))
1090
1091 (defvar *read-input-catch-tag* 0)
1092
1093 (defun intern-catch-tag (tag)
1094 ;; fixnums aren't eq in ABCL, so we use intern to create tags
1095 (intern (format nil "~D" tag) :swank))
1096
1097 (defun read-user-input-from-emacs ()
1098 (let ((tag (incf *read-input-catch-tag*)))
1099 (force-output)
1100 (send-to-emacs `(:read-string ,(current-thread) ,tag))
1101 (let ((ok nil))
1102 (unwind-protect
1103 (prog1 (catch (intern-catch-tag tag)
1104 (loop (read-from-emacs)))
1105 (setq ok t))
1106 (unless ok
1107 (send-to-emacs `(:read-aborted ,(current-thread) ,tag)))))))
1108
1109 (defun y-or-n-p-in-emacs (format-string &rest arguments)
1110 "Like y-or-n-p, but ask in the Emacs minibuffer."
1111 (let ((tag (incf *read-input-catch-tag*))
1112 (question (apply #'format nil format-string arguments)))
1113 (force-output)
1114 (send-to-emacs `(:y-or-n-p ,(current-thread) ,tag ,question))
1115 (catch (intern-catch-tag tag)
1116 (loop (read-from-emacs)))))
1117
1118 (defslimefun take-input (tag input)
1119 "Return the string INPUT to the continuation TAG."
1120 (throw (intern-catch-tag tag) input))
1121
1122 (defun process-form-for-emacs (form)
1123 "Returns a string which emacs will read as equivalent to
1124 FORM. FORM can contain lists, strings, characters, symbols and
1125 numbers.
1126
1127 Characters are converted emacs' ?<char> notaion, strings are left
1128 as they are (except for espacing any nested \" chars, numbers are
1129 printed in base 10 and symbols are printed as their symbol-nome
1130 converted to lower case."
1131 (etypecase form
1132 (string (format nil "~S" form))
1133 (cons (format nil "(~A . ~A)"
1134 (process-form-for-emacs (car form))
1135 (process-form-for-emacs (cdr form))))
1136 (character (format nil "?~C" form))
1137 (symbol (string-downcase (symbol-name form)))
1138 (number (let ((*print-base* 10))
1139 (princ-to-string form)))))
1140
1141 (defun eval-in-emacs (form &optional nowait)
1142 "Eval FORM in Emacs."
1143 (cond (nowait
1144 (send-to-emacs `(:eval-no-wait ,(process-form-for-emacs form))))
1145 (t
1146 (force-output)
1147 (let* ((tag (incf *read-input-catch-tag*))
1148 (value (catch (intern-catch-tag tag)
1149 (send-to-emacs
1150 `(:eval ,(current-thread) ,tag
1151 ,(process-form-for-emacs form)))
1152 (loop (read-from-emacs)))))
1153 (destructure-case value
1154 ((:ok value) value)
1155 ((:abort) (abort)))))))
1156
1157 (defslimefun connection-info ()
1158 "Return a key-value list of the form:
1159 \(&key PID STYLE LISP-IMPLEMENTATION MACHINE FEATURES PACKAGE)
1160 PID: is the process-id of Lisp process (or nil, depending on the STYLE)
1161 STYLE: the communication style
1162 LISP-IMPLEMENTATION: a list (&key TYPE NAME VERSION)
1163 FEATURES: a list of keywords
1164 PACKAGE: a list (&key NAME PROMPT)"
1165 (setq *slime-features* *features*)
1166 `(:pid ,(getpid) :style ,(connection.communication-style *emacs-connection*)
1167 :lisp-implementation (:type ,(lisp-implementation-type)
1168 :name ,(lisp-implementation-type-name)
1169 :version ,(lisp-implementation-version))
1170 :machine (:instance ,(machine-instance)
1171 :type ,(machine-type)
1172 :version ,(machine-version))
1173 :features ,(features-for-emacs)
1174 :package (:name ,(package-name *package*)
1175 :prompt ,(package-string-for-prompt *package*))))
1176
1177 (defslimefun io-speed-test (&optional (n 5000) (m 1))
1178 (let* ((s *standard-output*)
1179 (*trace-output* (make-broadcast-stream s *log-output*)))
1180 (time (progn
1181 (dotimes (i n)
1182 (format s "~D abcdefghijklm~%" i)
1183 (when (zerop (mod n m))
1184 (force-output s)))
1185 (finish-output s)
1186 (when *emacs-connection*
1187 (eval-in-emacs '(message "done.")))))
1188 (terpri *trace-output*)
1189 (finish-output *trace-output*)
1190 nil))
1191
1192
1193 ;;;; Reading and printing
1194
1195 (defmacro define-special (name doc)
1196 "Define a special variable NAME with doc string DOC.
1197 This is like defvar, but NAME will not be initialized."
1198 `(progn
1199 (defvar ,name)
1200 (setf (documentation ',name 'variable) ,doc)))
1201
1202 (define-special *buffer-package*
1203 "Package corresponding to slime-buffer-package.
1204
1205 EVAL-FOR-EMACS binds *buffer-package*. Strings originating from a slime
1206 buffer are best read in this package. See also FROM-STRING and TO-STRING.")
1207
1208 (define-special *buffer-readtable*
1209 "Readtable associated with the current buffer")
1210
1211 (defmacro with-buffer-syntax ((&rest _) &body body)
1212 "Execute BODY with appropriate *package* and *readtable* bindings.
1213
1214 This should be used for code that is conceptionally executed in an
1215 Emacs buffer."
1216 (destructuring-bind () _
1217 `(call-with-buffer-syntax (lambda () ,@body))))
1218
1219 (defun call-with-buffer-syntax (fun)
1220 (let ((*package* *buffer-package*))
1221 ;; Don't shadow *readtable* unnecessarily because that prevents
1222 ;; the user from assigning to it.
1223 (if (eq *readtable* *buffer-readtable*)
1224 (call-with-syntax-hooks fun)
1225 (let ((*readtable* *buffer-readtable*))
1226 (call-with-syntax-hooks fun)))))
1227
1228 (defun to-string (object)
1229 "Write OBJECT in the *BUFFER-PACKAGE*.
1230 The result may not be readable. Handles problems with PRINT-OBJECT methods
1231 gracefully."
1232 (with-buffer-syntax ()
1233 (let ((*print-readably* nil))
1234 (handler-case
1235 (prin1-to-string object)
1236 (error ()
1237 (with-output-to-string (s)
1238 (print-unreadable-object (object s :type t :identity t)
1239 (princ "<<error printing object>>" s))))))))
1240
1241 (defun from-string (string)
1242 "Read string in the *BUFFER-PACKAGE*"
1243 (with-buffer-syntax ()
1244 (let ((*read-suppress* nil))
1245 (read-from-string string))))
1246
1247 ;; FIXME: deal with #\| etc. hard to do portably.
1248 (defun tokenize-symbol (string)
1249 (let ((package (let ((pos (position #\: string)))
1250 (if pos (subseq string 0 pos) nil)))
1251 (symbol (let ((pos (position #\: string :from-end t)))
1252 (if pos (subseq string (1+ pos)) string)))
1253 (internp (search "::" string)))
1254 (values symbol package internp)))
1255
1256 ;; FIXME: Escape chars are ignored
1257 (defun casify (string)
1258 "Convert string accoring to readtable-case."
1259 (ecase (readtable-case *readtable*)
1260 (:preserve string)
1261 (:upcase (string-upcase string))
1262 (:downcase (string-downcase string))
1263 (:invert (multiple-value-bind (lower upper) (determine-case string)
1264 (cond ((and lower upper) string)
1265 (lower (string-upcase string))
1266 (upper (string-downcase string))
1267 (t string))))))
1268
1269 (defun parse-symbol (string &optional (package *package*))
1270 "Find the symbol named STRING.
1271 Return the symbol and a flag indicating whether the symbols was found."
1272 (multiple-value-bind (sname pname) (tokenize-symbol string)
1273 (let ((package (cond ((string= pname "") keyword-package)
1274 (pname (find-package (casify pname)))
1275 (t package))))
1276 (if package
1277 (find-symbol (casify sname) package)
1278 (values nil nil)))))
1279
1280 (defun parse-symbol-or-lose (string &optional (package *package*))
1281 (multiple-value-bind (symbol status) (parse-symbol string package)
1282 (if status
1283 (values symbol status)
1284 (error "Unknown symbol: ~A [in ~A]" string package))))
1285
1286 ;; FIXME: interns the name
1287 (defun parse-package (string)
1288 "Find the package named STRING.
1289 Return the package or nil."
1290 (multiple-value-bind (name pos)
1291 (if (zerop (length string))
1292 (values :|| 0)
1293 (let ((*package* keyword-package))
1294 (ignore-errors (read-from-string string))))
1295 (if (and (or (keywordp name) (stringp name))
1296 (= (length string) pos))
1297 (find-package name))))
1298
1299 (defun guess-package-from-string (name &optional (default-package *package*))
1300 (or (and name
1301 (or (parse-package name)
1302 (find-package (string-upcase name))
1303 (parse-package (substitute #\- #\! name))))
1304 default-package))
1305
1306 (defvar *readtable-alist* (default-readtable-alist)
1307 "An alist mapping package names to readtables.")
1308
1309 (defun guess-buffer-readtable (package-name &optional (default *readtable*))
1310 (let ((package (guess-package-from-string package-name)))
1311 (if package
1312 (or (cdr (assoc (package-name package) *readtable-alist*
1313 :test #'string=))
1314 default)
1315 default)))
1316
1317 (defun valid-operator-symbol-p (symbol)
1318 "Test if SYMBOL names a function, macro, or special-operator."
1319 (or (fboundp symbol)
1320 (macro-function symbol)
1321 (special-operator-p symbol)))
1322
1323 (defun valid-operator-name-p (string)
1324 "Test if STRING names a function, macro, or special-operator."
1325 (let ((symbol (parse-symbol string)))
1326 (valid-operator-symbol-p symbol)))
1327
1328
1329 ;;;; Arglists
1330
1331 (defslimefun arglist-for-echo-area (names)
1332 "Return the arglist for the first function, macro, or special-op in NAMES."
1333 (handler-case
1334 (with-buffer-syntax ()
1335 (let ((name (find-if (lambda (name)
1336 (or (consp name)
1337 (valid-operator-name-p name)))
1338 names)))
1339 (when name
1340 (multiple-value-bind (form operator-name)
1341 (operator-designator-to-form name)
1342 (format-arglist-for-echo-area form operator-name)))))
1343 (error (cond)
1344 (format nil "ARGLIST: ~A" cond))))
1345
1346 (defun operator-designator-to-form (name)
1347 (etypecase name
1348 (cons
1349 (destructure-case name
1350 ((:make-instance class-name)
1351 (values `(make-instance ',(parse-symbol class-name))
1352 'make-instance))
1353 ((:defmethod generic-name)
1354 (values `(defmethod ,(parse-symbol generic-name))
1355 'defmethod))))
1356 (string
1357 (values `(,(parse-symbol name))
1358 name))))
1359
1360 (defun clean-arglist (arglist)
1361 "Remove &whole, &enviroment, and &aux elements from ARGLIST."
1362 (cond ((null arglist) '())
1363 ((member (car arglist) '(&whole &environment))
1364 (clean-arglist (cddr arglist)))
1365 ((eq (car arglist) '&aux)
1366 '())
1367 (t (cons (car arglist) (clean-arglist (cdr arglist))))))
1368
1369 (defun arglist-to-string (arglist package)
1370 "Print the list ARGLIST for display in the echo area.
1371 The argument name are printed without package qualifiers and
1372 pretty printing of (function foo) as #'foo is suppressed."
1373 (setq arglist (clean-arglist arglist))
1374 (etypecase arglist
1375 (null "()")
1376 (cons
1377 (with-output-to-string (*standard-output*)
1378 (with-standard-io-syntax
1379 (let ((*package* package) (*print-case* :downcase)
1380 (*print-pretty* t) (*print-circle* nil) (*print-readably* nil)
1381 (*print-level* 10) (*print-length* 20))
1382 (pprint-logical-block (nil nil :prefix "(" :suffix ")")
1383 (loop
1384 (let ((arg (pop arglist)))
1385 (etypecase arg
1386 (symbol (princ arg))
1387 (string (princ arg))
1388 (cons (pprint-logical-block (nil nil :prefix "(" :suffix ")")
1389 (princ (car arg))
1390 (unless (null (cdr arg))
1391 (write-char #\space))
1392 (pprint-fill *standard-output* (cdr arg) nil))))
1393 (when (null arglist) (return))
1394 (write-char #\space)
1395 (pprint-newline :fill))))))))))
1396
1397 (defun test-print-arglist (list string)
1398 (string= (arglist-to-string list (find-package :swank)) string))
1399
1400 ;; Should work:
1401 (progn
1402 (assert (test-print-arglist '(function cons) "(function cons)"))
1403 (assert (test-print-arglist '(quote cons) "(quote cons)"))
1404 (assert (test-print-arglist '(&key (function #'+)) "(&key (function #'+))"))
1405 (assert (test-print-arglist '(&whole x y z) "(y z)"))
1406 (assert (test-print-arglist '(x &aux y z) "(x)"))
1407 (assert (test-print-arglist '(x &environment env y) "(x y)")))
1408 ;; Expected failure:
1409 ;; (assert (test-print-arglist '(&key ((function f))) "(&key ((function f)))"))
1410
1411 (defslimefun variable-desc-for-echo-area (variable-name)
1412 "Return a short description of VARIABLE-NAME, or NIL."
1413 (with-buffer-syntax ()
1414 (let ((sym (parse-symbol variable-name)))
1415 (if (and sym (boundp sym))
1416 (let ((*print-pretty* nil) (*print-level* 4)
1417 (*print-length* 10) (*print-circle* t))
1418 (format nil "~A => ~A" sym (symbol-value sym)))))))
1419
1420 (defstruct (keyword-arg
1421 (:conc-name keyword-arg.)
1422 (:constructor make-keyword-arg (keyword arg-name default-arg)))
1423 keyword
1424 arg-name
1425 default-arg)
1426
1427 (defun decode-keyword-arg (arg)
1428 "Decode a keyword item of formal argument list.
1429 Return three values: keyword, argument name, default arg."
1430 (cond ((symbolp arg)
1431 (make-keyword-arg (intern (symbol-name arg) keyword-package)
1432 arg
1433 nil))
1434 ((and (consp arg)
1435 (consp (car arg)))
1436 (make-keyword-arg (caar arg)
1437 (cadar arg)
1438 (cadr arg)))
1439 ((consp arg)
1440 (make-keyword-arg (intern (symbol-name (car arg)) keyword-package)
1441 (car arg)
1442 (cadr arg)))
1443 (t
1444 (error "Bad keyword item of formal argument list"))))
1445
1446 (defun encode-keyword-arg (arg)
1447 (if (eql (intern (symbol-name (keyword-arg.arg-name arg))
1448 keyword-package)
1449 (keyword-arg.keyword arg))
1450 (if (keyword-arg.default-arg arg)
1451 (list (keyword-arg.arg-name arg)
1452 (keyword-arg.default-arg arg))
1453 (keyword-arg.arg-name arg))
1454 (let ((keyword/name (list (keyword-arg.arg-name arg)
1455 (keyword-arg.keyword arg))))
1456 (if (keyword-arg.default-arg arg)
1457 (list keyword/name
1458 (keyword-arg.default-arg arg))
1459 (list keyword/name)))))
1460
1461 (progn
1462 (assert (equalp (decode-keyword-arg 'x)
1463 (make-keyword-arg :x 'x nil)))
1464 (assert (equalp (decode-keyword-arg '(x t))
1465 (make-keyword-arg :x 'x t)))
1466 (assert (equalp (decode-keyword-arg '((:x y)))
1467 (make-keyword-arg :x 'y nil)))
1468 (assert (equalp (decode-keyword-arg '((:x y) t))
1469 (make-keyword-arg :x 'y t))))
1470
1471 (defstruct (optional-arg
1472 (:conc-name optional-arg.)
1473 (:constructor make-optional-arg (arg-name default-arg)))
1474 arg-name
1475 default-arg)
1476
1477 (defun decode-optional-arg (arg)
1478 "Decode an optional item of a formal argument list.
1479 Return an OPTIONAL-ARG structure."
1480 (etypecase arg
1481 (symbol (make-optional-arg arg nil))
1482 (list (make-optional-arg (car arg) (cadr arg)))))
1483
1484 (defun encode-optional-arg (optional-arg)
1485 (if (optional-arg.default-arg optional-arg)
1486 (list (optional-arg.arg-name optional-arg)
1487 (optional-arg.default-arg optional-arg))
1488 (optional-arg.arg-name optional-arg)))
1489
1490 (progn
1491 (assert (equalp (decode-optional-arg 'x)
1492 (make-optional-arg 'x nil)))
1493 (assert (equalp (decode-optional-arg '(x t))
1494 (make-optional-arg 'x t))))
1495
1496 (defstruct (arglist (:conc-name arglist.))
1497 required-args ; list of the required arguments
1498 optional-args ; list of the optional arguments
1499 key-p ; whether &key appeared
1500 keyword-args ; list of the keywords
1501 rest ; name of the &rest or &body argument (if any)
1502 body-p ; whether the rest argument is a &body
1503 allow-other-keys-p) ; whether &allow-other-keys appeared
1504
1505 (defun decode-arglist (arglist)
1506 "Parse the list ARGLIST and return an ARGLIST structure."
1507 (let ((mode nil)
1508 (result (make-arglist)))
1509 (dolist (arg arglist)
1510 (cond
1511 ((eql arg '&allow-other-keys)
1512 (setf (arglist.allow-other-keys-p result) t))
1513 ((eql arg '&key)
1514 (setf (arglist.key-p result) t
1515 mode arg))
1516 ((member arg lambda-list-keywords)
1517 (setq mode arg))
1518 (t
1519 (case mode
1520 (&key
1521 (push (decode-keyword-arg arg)
1522 (arglist.keyword-args result)))
1523 (&optional
1524 (push (decode-optional-arg arg)
1525 (arglist.optional-args result)))
1526 (&body
1527 (setf (arglist.body-p result) t
1528 (arglist.rest result) arg))
1529 (&rest
1530 (setf (arglist.rest result) arg))
1531 ((nil)
1532 (push arg (arglist.required-args result)))
1533 ((&whole &environment)
1534 (setf mode nil))))))
1535 (setf (arglist.required-args result)
1536 (nreverse (arglist.required-args result)))
1537 (setf (arglist.optional-args result)
1538 (nreverse (arglist.optional-args result)))
1539 (setf (arglist.keyword-args result)
1540 (nreverse (arglist.keyword-args result)))
1541 result))
1542
1543 (defun encode-arglist (decoded-arglist)
1544 (append (arglist.required-args decoded-arglist)
1545 (when (arglist.optional-args decoded-arglist)
1546 '(&optional))
1547 (mapcar #'encode-optional-arg (arglist.optional-args decoded-arglist))
1548 (when (arglist.key-p decoded-arglist)
1549 '(&key))
1550 (mapcar #'encode-keyword-arg (arglist.keyword-args decoded-arglist))
1551 (when (arglist.allow-other-keys-p decoded-arglist)
1552 '(&allow-other-keys))
1553 (cond ((not (arglist.rest decoded-arglist))
1554 '())
1555 ((arglist.body-p decoded-arglist)
1556 `(&body ,(arglist.rest decoded-arglist)))
1557 (t
1558 `(&rest ,(arglist.rest decoded-arglist))))))
1559
1560 (defun arglist-keywords (arglist)
1561 "Return the list of keywords in ARGLIST.
1562 As a secondary value, return whether &allow-other-keys appears."
1563 (let ((decoded-arglist (decode-arglist arglist)))
1564 (values (arglist.keyword-args decoded-arglist)
1565 (arglist.allow-other-keys-p decoded-arglist))))
1566
1567 (defun methods-keywords (methods)
1568 "Collect all keywords in the arglists of METHODS.
1569 As a secondary value, return whether &allow-other-keys appears somewhere."
1570 (let ((keywords '())
1571 (allow-other-keys nil))
1572 (dolist (method methods)
1573 (multiple-value-bind (kw aok)
1574 (arglist-keywords
1575 (swank-mop:method-lambda-list method))
1576 (setq keywords (remove-duplicates (append keywords kw)
1577 :key #'keyword-arg.keyword)
1578 allow-other-keys (or allow-other-keys aok))))
1579 (values keywords allow-other-keys)))
1580
1581 (defun generic-function-keywords (generic-function)
1582 "Collect all keywords in the methods of GENERIC-FUNCTION.
1583 As a secondary value, return whether &allow-other-keys appears somewhere."
1584 (methods-keywords
1585 (swank-mop:generic-function-methods generic-function)))
1586
1587 (defun applicable-methods-keywords (generic-function classes)
1588 "Collect all keywords in the methods of GENERIC-FUNCTION that are
1589 applicable for argument of CLASSES. As a secondary value, return
1590 whether &allow-other-keys appears somewhere."
1591 (methods-keywords
1592 (swank-mop:compute-applicable-methods-using-classes
1593 generic-function classes)))
1594
1595 (defun decoded-arglist-to-template-string (decoded-arglist package &key (prefix "(") (suffix ")"))
1596 (with-output-to-string (*standard-output*)
1597 (with-standard-io-syntax
1598 (let ((*package* package) (*print-case* :downcase)
1599 (*print-pretty* t) (*print-circle* nil) (*print-readably* nil)
1600 (*print-level* 10) (*print-length* 20))
1601 (pprint-logical-block (nil nil :prefix prefix :suffix suffix)
1602 (print-decoded-arglist-as-template decoded-arglist))))))
1603
1604 (defun print-decoded-arglist-as-template (decoded-arglist)
1605 (let ((first-p t))
1606 (flet ((space ()
1607 (unless first-p
1608 (write-char #\space)
1609 (pprint-newline :fill))
1610 (setq first-p nil)))
1611 (dolist (arg (arglist.required-args decoded-arglist))
1612 (space)
1613 (princ arg))
1614 (dolist (arg (arglist.optional-args decoded-arglist))
1615 (space)
1616 (format t "[~A]" (optional-arg.arg-name arg)))
1617 (dolist (keyword-arg (arglist.keyword-args decoded-arglist))
1618 (space)
1619 (let ((arg-name (keyword-arg.arg-name keyword-arg))
1620 (keyword (keyword-arg.keyword keyword-arg)))
1621 (format t "~W ~A"
1622 (if (keywordp keyword) keyword `',keyword)
1623 arg-name)))
1624 (when (and (arglist.rest decoded-arglist)
1625 (or (not (arglist.keyword-args decoded-arglist))
1626 (arglist.allow-other-keys-p decoded-arglist)))
1627 (if (arglist.body-p decoded-arglist)
1628 (pprint-newline :mandatory)
1629 (space))
1630 (format t "~A..." (arglist.rest decoded-arglist)))))
1631 (pprint-newline :fill))
1632
1633 (defgeneric extra-keywords (operator &rest args)
1634 (:documentation "Return a list of extra keywords of OPERATOR (a
1635 symbol) when applied to the (unevaluated) ARGS.
1636 As a secondary value, return whether other keys are allowed.
1637 As a tertiary value, return the initial sublist of ARGS that was needed
1638 to determine the extra keywords."))
1639
1640 (defmethod extra-keywords (operator &rest args)
1641 ;; default method
1642 (declare (ignore args))
1643 (let ((symbol-function (symbol-function operator)))
1644 (if (typep symbol-function 'generic-function)
1645 (generic-function-keywords symbol-function)
1646 nil)))
1647
1648 (defmethod extra-keywords ((operator (eql 'make-instance))
1649 &rest args)
1650 (unless (null args)
1651 (let ((class-name-form (car args)))
1652 (when (and (listp class-name-form)
1653 (= (length class-name-form) 2)
1654 (eq (car class-name-form) 'quote))
1655 (let* ((class-name (cadr class-name-form))
1656 (class (find-class class-name nil)))
1657 (when (and class
1658 (not (swank-mop:class-finalized-p class)))
1659 ;; Try to finalize the class, which can fail if
1660 ;; superclasses are not defined yet
1661 (handler-case (swank-mop:finalize-inheritance class)
1662 (program-error (c)
1663 (declare (ignore c)))))
1664 (when class
1665 ;; We have the case (make-instance 'CLASS ...)
1666 ;; with a known CLASS.
1667 (multiple-value-bind (slots allow-other-keys-p)
1668 (if (swank-mop:class-finalized-p class)
1669 (values (swank-mop:class-slots class) nil)
1670 (values (swank-mop:class-direct-slots class) t))
1671 (let ((slot-init-keywords
1672 (loop for slot in slots append
1673 (mapcar (lambda (initarg)
1674 (make-keyword-arg
1675 initarg
1676 initarg ; FIXME
1677 (swank-mop:slot-definition-initform slot)))
1678 (swank-mop:slot-definition-initargs slot))))
1679 (initialize-instance-keywords
1680 (applicable-methods-keywords #'initialize-instance
1681 (list class))))
1682 (return-from extra-keywords
1683 (values (append slot-init-keywords
1684 initialize-instance-keywords)
1685 allow-other-keys-p
1686 (list class-name-form))))))))))
1687 (call-next-method))
1688
1689 (defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
1690 "Determine extra keywords from the function call FORM, and modify
1691 DECODED-ARGLIST to include them. As a secondary return value, return
1692 the initial sublist of ARGS that was needed to determine the extra
1693 keywords. As a tertiary return value, return whether any enrichment
1694 was done."
1695 (multiple-value-bind (extra-keywords extra-aok determining-args)
1696 (apply #'extra-keywords form)
1697 ;; enrich the list of keywords with the extra keywords
1698 (when extra-keywords
1699 (setf (arglist.key-p decoded-arglist) t)
1700 (setf (arglist.keyword-args decoded-arglist)
1701 (remove-duplicates
1702 (append (arglist.keyword-args decoded-arglist)
1703 extra-keywords)
1704 :key #'keyword-arg.keyword)))
1705 (setf (arglist.allow-other-keys-p decoded-arglist)
1706 (or (arglist.allow-other-keys-p decoded-arglist) extra-aok))
1707 (values decoded-arglist
1708 determining-args
1709 (or extra-keywords extra-aok))))
1710
1711 (defslimefun arglist-for-insertion (name)
1712 (with-buffer-syntax ()
1713 (let ((symbol (parse-symbol name)))
1714 (cond
1715 ((and symbol
1716 (valid-operator-name-p name))
1717 (let ((arglist (arglist symbol)))
1718 (etypecase arglist
1719 ((member :not-available)
1720 :not-available)
1721 (list
1722 (let ((decoded-arglist (decode-arglist arglist)))
1723 (enrich-decoded-arglist-with-extra-keywords decoded-arglist
1724 (list symbol))
1725 (decoded-arglist-to-template-string decoded-arglist
1726 *buffer-package*))))))
1727 (t
1728 :not-available)))))
1729
1730 (defvar *remove-keywords-alist*
1731 '((:test :test-not)
1732 (:test-not :test)))
1733
1734 (defun remove-actual-args (decoded-arglist actual-arglist)
1735 "Remove from DECODED-ARGLIST the arguments that have already been
1736 provided in ACTUAL-ARGLIST."
1737 (loop while (and actual-arglist
1738 (arglist.required-args decoded-arglist))
1739 do (progn (pop actual-arglist)
1740 (pop (arglist.required-args decoded-arglist))))
1741 (loop while (and actual-arglist
1742 (arglist.optional-args decoded-arglist))
1743 do (progn (pop actual-arglist)
1744 (pop (arglist.optional-args decoded-arglist))))
1745 (loop for keyword in actual-arglist by #'cddr
1746 for keywords-to-remove = (cdr (assoc keyword *remove-keywords-alist*))
1747 do (setf (arglist.keyword-args decoded-arglist)
1748 (remove-if (lambda (kw)
1749 (or (eql kw keyword)
1750 (member kw keywords-to-remove)))
1751 (arglist.keyword-args decoded-arglist)
1752 :key #'keyword-arg.keyword))))
1753
1754 (defgeneric form-completion (operator-form argument-forms &key remove-args))
1755
1756 (defmethod form-completion (operator-form argument-forms &key (remove-args t))
1757 (when (and (symbolp operator-form)
1758 (valid-operator-symbol-p operator-form))
1759 (let ((arglist (arglist operator-form)))
1760 (etypecase arglist
1761 ((member :not-available)
1762 :not-available)
1763 (list
1764 (let ((decoded-arglist (decode-arglist arglist)))
1765 (multiple-value-bind (decoded-arglist determining-args any-enrichment)
1766 (enrich-decoded-arglist-with-extra-keywords decoded-arglist
1767 (cons operator-form
1768 argument-forms))
1769 (cond
1770 (remove-args
1771 ;; get rid of formal args already provided
1772 (remove-actual-args decoded-arglist argument-forms))
1773 (t
1774 ;; replace some formal args by determining actual args
1775 (remove-actual-args decoded-arglist determining-args)
1776 (setf (arglist.required-args decoded-arglist)
1777 (append determining-args
1778 (arglist.required-args decoded-arglist)))))
1779 (return-from form-completion
1780 (values decoded-arglist any-enrichment))))))))
1781 :not-available)
1782
1783 (defmethod form-completion ((operator-form (eql 'defmethod))
1784 argument-forms &key (remove-args t))
1785 (when (and (listp argument-forms)
1786 (not (null argument-forms)) ;have generic function name
1787 (notany #'listp (rest argument-forms))) ;don't have arglist yet
1788 (let* ((gf-name (first argument-forms))
1789 (gf (and (or (symbolp gf-name)
1790 (and (listp gf-name)
1791 (eql (first gf-name) 'setf)))
1792 (fboundp gf-name)
1793 (fdefinition gf-name))))
1794 (when (typep gf 'generic-function)
1795 (let ((arglist (arglist gf)))
1796 (etypecase arglist
1797 ((member :not-available))
1798 (list
1799 (return-from form-completion
1800 (values (make-arglist :required-args (if remove-args
1801 (list arglist)
1802 (list gf-name arglist))
1803 :rest "body" :body-p t)
1804 t))))))))
1805 (call-next-method))
1806
1807 (defun read-incomplete-form-from-string (form-string)
1808 (with-buffer-syntax ()
1809 (handler-case
1810 (read-from-string form-string)
1811 (reader-error (c)
1812 (declare (ignore c))
1813 nil)
1814 (stream-error (c)
1815 (declare (ignore c))
1816 nil))))
1817
1818 (defslimefun complete-form (form-string)
1819 "Read FORM-STRING in the current buffer package, then complete it
1820 by adding a template for the missing arguments."
1821 (let ((form (read-incomplete-form-from-string form-string)))
1822 (when (consp form)
1823 (let ((operator-form (first form))
1824 (argument-forms (rest form)))
1825 (let ((form-completion
1826 (form-completion operator-form argument-forms)))
1827 (unless (eql form-completion :not-available)
1828 (return-from complete-form
1829 (decoded-arglist-to-template-string form-completion
1830 *buffer-package*
1831 :prefix ""))))))
1832 :not-available))
1833
1834 (defun format-arglist-for-echo-area (form &optional (operator-name (first form)))
1835 "Return the arglist for FORM as a string."
1836 (when (consp form)
1837 (let ((operator-form (first form))
1838 (argument-forms (rest form)))
1839 (multiple-value-bind (form-completion any-enrichment)
1840 (form-completion operator-form argument-forms
1841 :remove-args nil)
1842 (cond
1843 ((eql form-completion :not-available)
1844 nil)
1845 ((not any-enrichment)
1846 ;; Just use the original arglist.
1847 ;; This works better for implementation-specific
1848 ;; lambda-list-keywords like CMUCL's &parse-body.
1849 (let ((arglist (arglist operator-form)))
1850 (etypecase arglist
1851 ((member :not-available)
1852 nil)
1853 (list
1854 (return-from format-arglist-for-echo-area
1855 (arglist-to-string (cons operator-name arglist)
1856 *package*))))))
1857 (t
1858 (return-from format-arglist-for-echo-area
1859 (arglist-to-string
1860 (cons operator-name
1861 (encode-arglist form-completion))
1862 *package*)))))))
1863 nil)
1864
1865 (defslimefun completions-for-keyword (name keyword-string)
1866 (with-buffer-syntax ()
1867 (let* ((form (operator-designator-to-form name))
1868 (operator-form (first form))
1869 (argument-forms (rest form))
1870 (arglist
1871 (form-completion operator-form argument-forms
1872 :remove-args nil)))
1873 (unless (eql arglist :not-available)
1874 (let* ((keywords
1875 (mapcar #'keyword-arg.keyword
1876 (arglist.keyword-args arglist)))
1877 (keyword-name
1878 (tokenize-symbol keyword-string))
1879 (matching-keywords
1880 (find-matching-symbols-in-list keyword-name keywords
1881 #'compound-prefix-match))
1882 (converter (output-case-converter keyword-string))
1883 (strings
1884 (mapcar converter
1885 (mapcar #'symbol-name matching-keywords)))
1886 (completion-set
1887 (format-completion-set strings nil "")))
1888 (list completion-set
1889 (longest-completion completion-set)))))))
1890
1891
1892
1893 ;;;; Recording and accessing results of computations
1894
1895 (defvar *record-repl-results* t
1896 "Non-nil means that REPL results are saved for later lookup.")
1897
1898 (defvar *object-to-presentation-id*
1899 (make-weak-key-hash-table :test 'eq)
1900 "Store the mapping of objects to numeric identifiers")
1901
1902 (defvar *presentation-id-to-object*
1903 (make-weak-value-hash-table :test 'eql)
1904 "Store the mapping of numeric identifiers to objects")
1905
1906 (defun clear-presentation-tables ()
1907 (clrhash *object-to-presentation-id*)
1908 (clrhash *presentation-id-to-object*))
1909
1910 (defvar *presentation-counter* 0 "identifier counter")
1911
1912 ;; XXX thread safety?
1913 (defun save-presented-object (object)
1914 "Save OBJECT and return the assigned id.
1915 If OBJECT was saved previously return the old id."
1916 (or (gethash object *object-to-presentation-id*)
1917 (let ((id (incf *presentation-counter*)))
1918 (setf (gethash id *presentation-id-to-object*) object)
1919 (setf (gethash object *object-to-presentation-id*) id)
1920 id)))
1921
1922 (defun lookup-presented-object (id)
1923 "Retrieve the object corresponding to ID.
1924 The secondary value indicates the absence of an entry."
1925 (gethash id *presentation-id-to-object*))
1926
1927 (defslimefun get-repl-result (id)
1928 "Get the result of the previous REPL evaluation with ID."
1929 (multiple-value-bind (object foundp) (lookup-presented-object id)
1930 (cond (foundp object)
1931 (t (error "Attempt to access unrecorded object (id ~D)." id)))))
1932
1933 (defslimefun clear-repl-results ()
1934 "Forget the results of all previous REPL evaluations."
1935 (clear-presentation-tables)
1936 t)
1937
1938
1939 ;;;; Evaluation
1940
1941 (defvar *pending-continuations* '()
1942 "List of continuations for Emacs. (thread local)")
1943
1944 (defun guess-buffer-package (string)
1945 "Return a package for STRING.
1946 Fall back to the the current if no such package exists."
1947 (or (guess-package-from-string string nil)
1948 *package*))
1949
1950 (defun eval-for-emacs (form buffer-package id)
1951 "Bind *BUFFER-PACKAGE* BUFFER-PACKAGE and evaluate FORM.
1952 Return the result to the continuation ID.
1953 Errors are trapped and invoke our debugger."
1954 (call-with-debugger-hook
1955 #'swank-debugger-hook
1956 (lambda ()
1957 (let (ok result)
1958 (unwind-protect
1959 (let ((*buffer-package* (guess-buffer-package buffer-package))
1960 (*buffer-readtable* (guess-buffer-readtable buffer-package))
1961 (*pending-continuations* (cons id *pending-continuations*)))
1962 (check-type *buffer-package* package)
1963 (check-type *buffer-readtable* readtable)
1964 ;; APPLY would be cleaner than EVAL.
1965 ;;(setq result (apply (car form) (cdr form)))
1966 (setq result (eval form))
1967 (finish-output)
1968 (run-hook *pre-reply-hook*)
1969 (setq ok t))
1970 (force-user-output)
1971 (send-to-emacs `(:return ,(current-thread)
1972 ,(if ok `(:ok ,result) '(:abort))
1973 ,id)))))))
1974
1975 (defvar *echo-area-prefix* "=> "
1976 "A prefix that `format-values-for-echo-area' should use.")
1977
1978 (defun format-values-for-echo-area (values)
1979 (with-buffer-syntax ()
1980 (let ((*print-readably* nil))
1981 (cond ((null values) "; No value")
1982 ((and (null (cdr values)) (integerp (car values)))
1983 (let ((i (car values)))
1984 (format nil "~A~D (#x~X, #o~O, #b~B)"
1985 *echo-area-prefix* i i i i)))
1986 (t (format nil "~A~{~S~^, ~}" *echo-area-prefix* values))))))
1987
1988 (defslimefun interactive-eval (string)
1989 (with-buffer-syntax ()
1990 (let ((values (multiple-value-list (eval (from-string string)))))
1991 (fresh-line)
1992 (finish-output)
1993 (format-values-for-echo-area values))))
1994
1995 (defslimefun eval-and-grab-output (string)
1996 (with-buffer-syntax ()
1997 (let* ((s (make-string-output-stream))
1998 (*standard-output* s)
1999 (values (multiple-value-list (eval (from-string string)))))
2000 (list (get-output-stream-string s)
2001 (format nil "~{~S~^~%~}" values)))))
2002
2003 ;;; XXX do we need this stuff? What is it good for?
2004 (defvar *slime-repl-advance-history* nil
2005 "In the dynamic scope of a single form typed at the repl, is set to nil to
2006 prevent the repl from advancing the history - * ** *** etc.")
2007
2008 (defvar *slime-repl-suppress-output* nil
2009 "In the dynamic scope of a single form typed at the repl, is set to nil to
2010 prevent the repl from printing the result of the evalation.")
2011
2012 (defvar *slime-repl-eval-hook-pass* (gensym "PASS")
2013 "Token to indicate that a repl hook declines to evaluate the form")
2014
2015 (defvar *slime-repl-eval-hooks* nil
2016 "A list of functions. When the repl is about to eval a form, first try running each of
2017 these hooks. The first hook which returns a value which is not *slime-repl-eval-hook-pass*
2018 is considered a replacement for calling eval. If there are no hooks, or all
2019 pass, then eval is used.")
2020
2021 (defslimefun repl-eval-hook-pass ()
2022 "call when repl hook declines to evaluate the form"
2023 (throw *slime-repl-eval-hook-pass* *slime-repl-eval-hook-pass*))
2024
2025 (defslimefun repl-suppress-output ()
2026 "In the dynamic scope of a single form typed at the repl, call to
2027 prevent the repl from printing the result of the evalation."
2028 (setq *slime-repl-suppress-output* t))
2029
2030 (defslimefun repl-suppress-advance-history ()
2031 "In the dynamic scope of a single form typed at the repl, call to
2032 prevent the repl from advancing the history - * ** *** etc."
2033 (setq *slime-repl-advance-history* nil))
2034
2035 (defun eval-region (string &optional package-update-p)
2036 "Evaluate STRING and return the result.
2037 If PACKAGE-UPDATE-P is non-nil, and evaluation causes a package
2038 change, then send Emacs an update."
2039 (unwind-protect
2040 (with-input-from-string (stream string)
2041 (let (- values)
2042 (loop
2043 (let ((form (read stream nil stream)))
2044 (when (eq form stream)
2045 (fresh-line)
2046 (finish-output)
2047 (return (values values -)))
2048 (setq - form)
2049 (if *slime-repl-eval-hooks*
2050 (setq values (run-repl-eval-hooks form))
2051 (setq values (multiple-value-list (eval form))))
2052 (finish-output)))))
2053 (when (and package-update-p (not (eq *package* *buffer-package*)))
2054 (send-to-emacs
2055 (list :new-package (package-name *package*)
2056 (package-string-for-prompt *package*))))))
2057
2058 (defun run-repl-eval-hooks (form)
2059 (loop for hook in *slime-repl-eval-hooks*
2060 for res = (catch *slime-repl-eval-hook-pass*
2061 (multiple-value-list (funcall hook form)))
2062 until (not (eq res *slime-repl-eval-hook-pass*))
2063 finally (return
2064 (if (eq res *slime-repl-eval-hook-pass*)
2065 (multiple-value-list (eval form))
2066 res))))
2067
2068 (defun package-string-for-prompt (package)
2069 "Return the shortest nickname (or canonical name) of PACKAGE."
2070 (princ-to-string
2071 (make-symbol
2072 (or (canonical-package-nickname package)
2073 (auto-abbreviated-package-name package)
2074 (shortest-package-nickname package)))))
2075
2076 (defun canonical-package-nickname (package)
2077 "Return the canonical package nickname, if any, of PACKAGE."
2078 (let ((name (cdr (assoc (package-name package) *canonical-package-nicknames*
2079 :test #'string=))))
2080 (and name (string name))))
2081
2082 (defun auto-abbreviated-package-name (package)
2083 "Return an abbreviated 'name' for PACKAGE.
2084
2085 N.B. this is not an actual package name or nickname."
2086 (when *auto-abbreviate-dotted-packages*
2087 (let ((last-dot (position #\. (package-name package) :from-end t)))
2088 (when last-dot (subseq (package-name package) (1+ last-dot))))))
2089
2090 (defun shortest-package-nickname (package)
2091 "Return the shortest nickname (or canonical name) of PACKAGE."
2092 (loop for name in (cons (package-name package) (package-nicknames package))
2093 for shortest = name then (if (< (length name) (length shortest))
2094 name
2095 shortest)
2096 finally (return shortest)))
2097
2098 (defslimefun interactive-eval-region (string)
2099 (with-buffer-syntax ()
2100 (format-values-for-echo-area (eval-region string))))
2101
2102 (defslimefun re-evaluate-defvar (form)
2103 (with-buffer-syntax ()
2104 (let ((form (read-from-string form)))
2105 (destructuring-bind (dv name &optional value doc) form
2106 (declare (ignore value doc))
2107 (assert (eq dv 'defvar))
2108 (makunbound name)
2109 (prin1-to-string (eval form))))))
2110
2111 (defvar *swank-pprint-bindings*
2112 `((*print-pretty* . t)
2113 (*print-level* . nil)
2114 (*print-length* . nil)
2115 (*print-circle* . t)
2116 (*print-gensym* . t)
2117 (*print-readably* . nil))
2118 "A list of variables bindings during pretty printing.
2119 Used by pprint-eval.")
2120
2121 (defun swank-pprint (list)
2122 "Bind some printer variables and pretty print each object in LIST."
2123 (with-buffer-syntax ()
2124 (with-bindings *swank-pprint-bindings*
2125 (cond ((null list) "; No value")
2126 (t (with-output-to-string (*standard-output*)
2127 (dolist (o list)
2128 (pprint o)
2129 (terpri))))))))
2130
2131 (defslimefun pprint-eval (string)
2132 (with-buffer-syntax ()
2133 (swank-pprint (multiple-value-list (eval (read-from-string string))))))
2134
2135 (defslimefun set-package (package)
2136 "Set *package* to PACKAGE.
2137 Return its name and the string to use in the prompt."
2138 (let ((p (setq *package* (guess-package-from-string package))))
2139 (list (package-name p) (package-string-for-prompt p))))
2140
2141 (defslimefun listener-eval (string)
2142 (clear-user-input)
2143 (with-buffer-syntax ()
2144 (let ((*slime-repl-suppress-output* :unset)
2145 (*slime-repl-advance-history* :unset))
2146 (multiple-value-bind (values last-form) (eval-region string t)
2147 (unless (or (and (eq values nil) (eq last-form nil))
2148 (eq *slime-repl-advance-history* nil))
2149 (setq *** ** ** * * (car values)
2150 /// // // / / values))
2151 (setq +++ ++ ++ + + last-form)
2152 (cond ((eq *slime-repl-suppress-output* t) '(:suppress-output))
2153 (*record-repl-results*
2154 `(:present ,(loop for x in values
2155 collect (cons (prin1-to-string x)
2156 (save-presented-object x)))))
2157 (t
2158 `(:values ,(mapcar #'prin1-to-string values))))))))
2159
2160 (defslimefun ed-in-emacs (&optional what)
2161 "Edit WHAT in Emacs.
2162
2163 WHAT can be:
2164 A pathname or a string,
2165 A list (PATHNAME-OR-STRING LINE [COLUMN]),
2166 A function name (symbol),
2167 NIL.
2168
2169 Returns true if it actually called emacs, or NIL if not."
2170 (flet ((pathname-or-string-p (thing)
2171 (or (pathnamep thing) (typep thing 'string))))
2172 (let ((target
2173 (cond ((and (listp what) (pathname-or-string-p (first what)))
2174 (cons (canonicalize-filename (car what)) (cdr what)))
2175 ((pathname-or-string-p what)
2176 (canonicalize-filename what))
2177 ((symbolp what) what)
2178 (t (return-from ed-in-emacs nil)))))
2179 (send-oob-to-emacs `(:ed ,target))
2180 t)))
2181
2182 (defslimefun value-for-editing (form)
2183 "Return a readable value of FORM for editing in Emacs.
2184 FORM is expected, but not required, to be SETF'able."
2185 ;; FIXME: Can we check FORM for setfability? -luke (12/Mar/2005)
2186 (with-buffer-syntax ()
2187 (prin1-to-string (eval (read-from-string form)))))
2188
2189 (defslimefun commit-edited-value (form value)
2190 "Set the value of a setf'able FORM to VALUE.
2191 FORM and VALUE are both strings from Emacs."
2192 (with-buffer-syntax ()
2193 (eval `(setf ,(read-from-string form)
2194 ,(read-from-string (concatenate 'string "`" value))))
2195 t))
2196
2197 (defun background-message (format-string &rest args)
2198 "Display a message in Emacs' echo area.
2199
2200 Use this function for informative messages only. The message may even
2201 be dropped, if we are too busy with other things."
2202 (when *emacs-connection*
2203 (send-to-emacs `(:background-message
2204 ,(apply #'format nil format-string args)))))
2205
2206
2207 ;;;; Debugger
2208
2209 (defun swank-debugger-hook (condition hook)
2210 "Debugger function for binding *DEBUGGER-HOOK*.
2211 Sends a message to Emacs declaring that the debugger has been entered,
2212 then waits to handle further requests from Emacs. Eventually returns
2213 after Emacs causes a restart to be invoked."
2214 (declare (ignore hook))
2215 (cond (*emacs-connection*
2216 (debug-in-emacs condition))
2217 ((default-connection)
2218 (with-connection ((default-connection))
2219 (debug-in-emacs condition)))))
2220
2221 (defvar *global-debugger* t
2222 "Non-nil means the Swank debugger hook will be installed globally.")
2223
2224 (add-hook *new-connection-hook* 'install-debugger)
2225 (defun install-debugger (connection)
2226 (declare (ignore connection))
2227 (when *global-debugger*
2228 (install-debugger-globally #'swank-debugger-hook)))
2229
2230 ;;;;; Debugger loop
2231 ;;;
2232 ;;; These variables are dynamically bound during debugging.
2233 ;;;
2234 (defvar *swank-debugger-condition* nil
2235 "The condition being debugged.")
2236
2237 (defvar *sldb-level* 0
2238 "The current level of recursive debugging.")
2239
2240 (defvar *sldb-initial-frames* 20
2241 "The initial number of backtrace frames to send to Emacs.")
2242
2243 (defvar *sldb-restarts* nil
2244 "The list of currenlty active restarts.")
2245
2246 (defvar *sldb-stepping-p* nil
2247 "True when during execution of a stepp command.")
2248
2249 (defun debug-in-emacs (condition)
2250 (let ((*swank-debugger-condition* condition)
2251 (*sldb-restarts* (compute-restarts condition))
2252 (*package* (or (and (boundp '*buffer-package*)
2253 (symbol-value '*buffer-package*))
2254 *package*))
2255 (*sldb-level* (1+ *sldb-level*))
2256 (*sldb-stepping-p* nil)
2257 (*swank-state-stack* (cons :swank-debugger-hook *swank-state-stack*)))
2258 (force-user-output)
2259 (with-bindings *sldb-printer-bindings*
2260 (call-with-debugging-environment
2261 (lambda () (sldb-loop *sldb-level*))))))
2262
2263 (defun sldb-loop (level)
2264 (unwind-protect
2265 (catch 'sldb-enter-default-debugger
2266 (send-to-emacs
2267 (list* :debug (current-thread) level
2268 (debugger-info-for-emacs 0 *sldb-initial-frames*)))
2269 (loop (catch 'sldb-loop-catcher
2270 (with-simple-restart (abort "Return to sldb level ~D." level)
2271 (send-to-emacs (list :debug-activate (current-thread)
2272 level))
2273 (handler-bind ((sldb-condition #'handle-sldb-condition))
2274 (read-from-emacs))))))
2275 (send-to-emacs `(:debug-return
2276 ,(current-thread) ,level ,*sldb-stepping-p*))))
2277
2278 (defun handle-sldb-condition (condition)
2279 "Handle an internal debugger condition.
2280 Rather than recursively debug the debugger (a dangerous idea!), these
2281 conditions are simply reported."
2282 (let ((real-condition (original-condition condition)))
2283 (send-to-emacs `(:debug-condition ,(current-thread)
2284 ,(princ-to-string real-condition))))
2285 (throw 'sldb-loop-catcher nil))
2286
2287 (defun safe-condition-message (condition)
2288 "Safely print condition to a string, handling any errors during
2289 printing."
2290 (let ((*print-pretty* t))
2291 (handler-case
2292 (format-sldb-condition condition)
2293 (error (cond)
2294 ;; Beware of recursive errors in printing, so only use the condition
2295 ;; if it is printable itself:
2296 (format nil "Unable to display error condition~@[: ~A~]"
2297 (ignore-errors (princ-to-string cond)))))))
2298
2299 (defun debugger-condition-for-emacs ()
2300 (list (safe-condition-message *swank-debugger-condition*)
2301 (format nil " [Condition of type ~S]"
2302 (type-of *swank-debugger-condition*))
2303 (condition-references *swank-debugger-condition*)
2304 (condition-extras *swank-debugger-condition*)))
2305
2306 (defun format-restarts-for-emacs ()
2307 "Return a list of restarts for *swank-debugger-condition* in a
2308 format suitable for Emacs."
2309 (loop for restart in *sldb-restarts*
2310 collect (list (princ-to-string (restart-name restart))
2311 (princ-to-string restart))))
2312
2313 (defun frame-for-emacs (n frame)
2314 (let* ((label (format nil " ~2D: " n))
2315 (string (with-output-to-string (stream)
2316 (princ label stream)
2317 (print-frame frame stream))))
2318 (subseq string (length label))))
2319
2320 ;;;;; SLDB entry points
2321
2322 (defslimefun sldb-break-with-default-debugger ()
2323 "Invoke the default debugger by returning from our debugger-loop."
2324 (throw 'sldb-enter-default-debugger nil))
2325
2326 (defslimefun backtrace (start end)
2327 "Return a list ((I FRAME) ...) of frames from START to END.
2328 I is an integer describing and FRAME a string."
2329 (loop for frame in (compute-backtrace start end)
2330 for i from start
2331 collect (list i (frame-for-emacs i frame))))
2332
2333 (defslimefun debugger-info-for-emacs (start end)
2334 "Return debugger state, with stack frames from START to END.
2335 The result is a list:
2336 (condition ({restart}*) ({stack-frame}*) (cont*))
2337 where
2338 condition ::= (description type [extra])
2339 restart ::= (name description)
2340 stack-frame ::= (number description)
2341 extra ::= (:references and other random things)
2342 cont ::= continutation
2343 condition---a pair of strings: message, and type. If show-source is
2344 not nil it is a frame number for which the source should be displayed.
2345
2346 restart---a pair of strings: restart name, and description.
2347
2348 stack-frame---a number from zero (the top), and a printed
2349 representation of the frame's call.
2350
2351 continutation---the id of a pending Emacs continuation.
2352
2353 Below is an example return value. In this case the condition was a
2354 division by zero (multi-line description), and only one frame is being
2355 fetched (start=0, end=1).
2356
2357 ((\"Arithmetic error DIVISION-BY-ZERO signalled.
2358 Operation was KERNEL::DIVISION, operands (1 0).\"
2359 \"[Condition of type DIVISION-BY-ZERO]\")
2360 ((\"ABORT\" \"Return to Slime toplevel.\")
2361 (\"ABORT\" \"Return to Top-Level.\"))
2362 ((0 \"(KERNEL::INTEGER-/-INTEGER 1 0)\"))
2363 (4))"
2364 (list (debugger-condition-for-emacs)
2365 (format-restarts-for-emacs)
2366 (backtrace start end)
2367 *pending-continuations*))
2368
2369 (defun nth-restart (index)
2370 (nth index *sldb-restarts*))
2371
2372 (defslimefun invoke-nth-restart (index)
2373 (invoke-restart-interactively (nth-restart index)))
2374
2375 (defslimefun sldb-abort ()
2376 (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))
2377
2378 (defslimefun sldb-continue ()
2379 (continue))
2380
2381 (defslimefun throw-to-toplevel ()
2382 "Invoke the ABORT-REQUEST restart abort an RPC from Emacs.
2383 If we are not evaluating an RPC then ABORT instead."
2384 (let ((restart (find-restart 'abort-request)))
2385 (cond (restart (invoke-restart restart))
2386 (t "Restart not found: ABORT-REQUEST"))))
2387
2388 (defslimefun invoke-nth-restart-for-emacs (sldb-level n)
2389 "Invoke the Nth available restart.
2390 SLDB-LEVEL is the debug level when the request was made. If this
2391 has changed, ignore the request."
2392 (when (= sldb-level *sldb-level*)
2393 (invoke-nth-restart n)))
2394
2395 (defun wrap-sldb-vars (form)
2396 `(let ((*sldb-level* ,*sldb-level*))
2397 ,form))
2398
2399 (defslimefun eval-string-in-frame (string index)
2400 (to-string (eval-in-frame (wrap-sldb-vars (from-string string))
2401 index)))
2402
2403 (defslimefun pprint-eval-string-in-frame (string index)
2404 (swank-pprint
2405 (multiple-value-list
2406 (eval-in-frame (wrap-sldb-vars (from-string string)) index))))
2407
2408 (defslimefun frame-locals-for-emacs (index)
2409 "Return a property list ((&key NAME ID VALUE) ...) describing
2410 the local variables in the frame INDEX."
2411 (mapcar (lambda (frame-locals)
2412 (destructuring-bind (&key name id value) frame-locals
2413 (list :name (prin1-to-string name) :id id
2414 :value (to-string value))))
2415 (frame-locals index)))
2416
2417 (defslimefun frame-catch-tags-for-emacs (frame-index)
2418 (mapcar #'to-string (frame-catch-tags frame-index)))
2419
2420 (defslimefun sldb-disassemble (index)
2421 (with-output-to-string (*standard-output*)
2422 (disassemble-frame index)))
2423
2424 (defslimefun sldb-return-from-frame (index string)
2425 (let ((form (from-string string)))
2426 (to-string (multiple-value-list (return-from-frame index form)))))
2427
2428 (defslimefun sldb-break (name)
2429 (with-buffer-syntax ()
2430 (sldb-break-at-start (read-from-string name))))
2431
2432 (defslimefun sldb-step (frame)
2433 (cond ((find-restart 'continue)
2434 (activate-stepping frame)
2435 (setq *sldb-stepping-p* t)
2436 (continue))
2437 (t
2438 (error "No continue restart."))))
2439
2440
2441 ;;;; Compilation Commands.
2442
2443 (defvar *compiler-notes* '()
2444 "List of compiler notes for the last compilation unit.")
2445
2446 (defun clear-compiler-notes ()
2447 (setf *compiler-notes* '()))
2448
2449 (defun canonicalize-filename (filename)
2450 (namestring (truename filename)))
2451
2452 (defslimefun compiler-notes-for-emacs ()
2453 "Return the list of compiler notes for the last compilation unit."
2454 (reverse *compiler-notes*))
2455
2456 (defun measure-time-interval (fn)
2457 "Call FN and return the first return value and the elapsed time.
2458 The time is measured in microseconds."
2459 (declare (type function fn))
2460 (let ((before (get-internal-real-time)))
2461 (values
2462 (funcall fn)
2463 (* (- (get-internal-real-time) before)
2464 (/ 1000000 internal-time-units-per-second)))))
2465
2466 (defun record-note-for-condition (condition)
2467 "Record a note for a compiler-condition."
2468 (push (make-compiler-note condition) *compiler-notes*))
2469
2470 (defun make-compiler-note (condition)
2471 "Make a compiler note data structure from a compiler-condition."
2472 (declare (type compiler-condition condition))
2473 (list* :message (message condition)
2474 :severity (severity condition)
2475 :location (location condition)
2476 :references (references condition)
2477 (let ((s (short-message condition)))
2478 (if s (list :short-message s)))))
2479
2480 (defun swank-compiler (function)
2481 (clear-compiler-notes)
2482 (with-simple-restart (abort "Abort SLIME compilation.")
2483 (multiple-value-bind (result usecs)
2484 (handler-bind ((compiler-condition #'record-note-for-condition))
2485 (measure-time-interval function))
2486 (list (to-string result)
2487 (format nil "~,2F" (/ usecs 1000000.0))))))
2488
2489 (defslimefun compile-file-for-emacs (filename load-p &optional external-format)
2490 "Compile FILENAME and, when LOAD-P, load the result.
2491 Record compiler notes signalled as `compiler-condition's."
2492 (with-buffer-syntax ()
2493 (let ((*compile-print* nil))
2494 (swank-compiler (lambda () (swank-compile-file filename load-p
2495 external-format))))))
2496
2497 (defslimefun compile-string-for-emacs (string buffer position directory)
2498 "Compile STRING (exerpted from BUFFER at POSITION).
2499 Record compiler notes signalled as `compiler-condition's."
2500 (with-buffer-syntax ()
2501 (swank-compiler
2502 (lambda ()
2503 (let ((*compile-print* nil) (*compile-verbose* t))
2504 (swank-compile-string string :buffer buffer :position position
2505 :directory directory))))))
2506
2507 (defslimefun operate-on-system-for-emacs (system-name operation &rest keywords)
2508 "Compile and load SYSTEM using ASDF.
2509 Record compiler notes signalled as `compiler-condition's."
2510 (swank-compiler
2511 (lambda ()
2512 (apply #'operate-on-system system-name operation keywords))))
2513
2514 (defun asdf-central-registry ()
2515 (when (find-package :asdf)
2516 (symbol-value (find-symbol (string :*central-registry*) :asdf))))
2517
2518 (defslimefun list-all-systems-in-central-registry ()
2519 "Returns a list of all systems in ASDF's central registry."
2520 (delete-duplicates
2521 (loop for dir in (asdf-central-registry)
2522 for defaults = (eval dir)
2523 when defaults
2524 nconc (mapcar #'file-namestring
2525 (directory
2526 (make-pathname :defaults defaults
2527 :version :newest
2528 :type "asd"
2529 :name :wild
2530 :case :local))))
2531 :test #'string=))
2532
2533 (defun file-newer-p (new-file old-file)
2534 "Returns true if NEW-FILE is newer than OLD-FILE."
2535 (> (file-write-date new-file) (file-write-date old-file)))
2536
2537 (defun requires-compile-p (source-file)
2538 (let ((fasl-file (probe-file (compile-file-pathname source-file))))
2539 (or (not fasl-file)
2540 (file-newer-p source-file fasl-file))))
2541
2542 (defslimefun compile-file-if-needed (filename loadp)
2543 (cond ((requires-compile-p filename)
2544 (compile-file-for-emacs filename loadp))
2545 (loadp
2546 (load (compile-file-pathname filename))
2547 nil)))
2548
2549
2550 ;;;; Loading
2551
2552 (defslimefun load-file (filename)
2553 (to-string (load filename)))
2554
2555 (defslimefun load-file-set-package (filename &optional package)
2556 (load-file filename)
2557 (if package
2558 (set-package package)))
2559
2560
2561 ;;;; Macroexpansion
2562
2563 (defvar *macroexpand-printer-bindings*
2564 '((*print-circle* . nil)
2565 (*print-pretty* . t)
2566 (*print-escape* . t)
2567 (*print-level* . nil)
2568 (*print-length* . nil)))
2569
2570 (defun apply-macro-expander (expander string)
2571 (declare (type function expander))
2572 (with-buffer-syntax ()
2573 (with-bindings *macroexpand-printer-bindings*
2574 (prin1-to-string (funcall expander (from-string string))))))
2575
2576 (defslimefun swank-macroexpand-1 (string)
2577 (apply-macro-expander #'macroexpand-1 string))
2578
2579 (defslimefun swank-macroexpand (string)
2580 (apply-macro-expander #'macroexpand string))
2581
2582 (defslimefun swank-macroexpand-all (string)
2583 (apply-macro-expander #'macroexpand-all string))
2584
2585 (defslimefun swank-compiler-macroexpand-1 (string)
2586 (apply-macro-expander #'compiler-macroexpand-1 string))
2587
2588 (defslimefun swank-compiler-macroexpand (string)
2589 (apply-macro-expander #'compiler-macroexpand string))
2590
2591 (defslimefun disassemble-symbol (name)
2592 (with-buffer-syntax ()
2593 (with-output-to-string (*standard-output*)
2594 (let ((*print-readably* nil))
2595 (disassemble (fdefinition (from-string name)))))))
2596
2597
2598 ;;;; Basic completion
2599
2600 (defslimefun completions (string default-package-name)
2601 "Return a list of completions for a symbol designator STRING.
2602
2603 The result is the list (COMPLETION-SET
2604 COMPLETED-PREFIX). COMPLETION-SET is the list of all matching
2605 completions, and COMPLETED-PREFIX is the best (partial)
2606 completion of the input string.
2607
2608 If STRING is package qualified the result list will also be
2609 qualified. If string is non-qualified the result strings are
2610 also not qualified and are considered relative to
2611 DEFAULT-PACKAGE-NAME.
2612
2613 The way symbols are matched depends on the symbol designator's
2614 format. The cases are as follows:
2615 FOO - Symbols with matching prefix and accessible in the buffer package.
2616 PKG:FOO - Symbols with matching prefix and external in package PKG.
2617 PKG::FOO - Symbols with matching prefix and accessible in package PKG."
2618 (let ((completion-set (completion-set string default-package-name
2619 #'compound-prefix-match)))
2620 (list completion-set (longest-completion completion-set))))
2621
2622 (defslimefun simple-completions (string default-package-name)
2623 "Return a list of completions for a symbol designator STRING."
2624 (let ((completion-set (completion-set string default-package-name
2625 #'prefix-match-p)))
2626 (list completion-set (longest-common-prefix completion-set))))
2627
2628 ;;;;; Find completion set
2629
2630 (defun completion-set (string default-package-name matchp)
2631 "Return the set of completion-candidates as strings."
2632 (multiple-value-bind (name package-name package internal-p)
2633 (parse-completion-arguments string default-package-name)
2634 (let* ((symbols (and package
2635 (find-matching-symbols name
2636 package
2637 (and (not internal-p)
2638 package-name)
2639 matchp)))
2640 (packs (and (not package-name)
2641 (find-matching-packages name matchp)))
2642 (converter (output-case-converter name))
2643 (strings
2644 (mapcar converter
2645 (nconc (mapcar #'symbol-name symbols) packs))))
2646 (format-completion-set strings internal-p package-name))))
2647
2648 (defun find-matching-symbols (string package external test)
2649 "Return a list of symbols in PACKAGE matching STRING.
2650 TEST is called with two strings. If EXTERNAL is true, only external
2651 symbols are returned."
2652 (let ((completions '())
2653 (converter (output-case-converter string)))
2654 (flet ((symbol-matches-p (symbol)
2655 (and (or (not external)
2656 (symbol-external-p symbol package))
2657 (funcall test string
2658 (funcall converter (symbol-name symbol))))))
2659 (do-symbols (symbol package)
2660 (when (symbol-matches-p symbol)
2661 (push symbol completions))))
2662 (remove-duplicates completions)))
2663
2664 (defun find-matching-symbols-in-list (string list test)
2665 "Return a list of symbols in LIST matching STRING.
2666 TEST is called with two strings."
2667 (let ((completions '())
2668 (converter (output-case-converter string)))
2669 (flet ((symbol-matches-p (symbol)
2670 (funcall test string
2671 (funcall converter (symbol-name symbol)))))
2672 (dolist (symbol list)
2673 (when (symbol-matches-p symbol)
2674 (push symbol completions))))
2675 (remove-duplicates completions)))
2676
2677 (defun symbol-external-p (symbol &optional (package (symbol-package symbol)))
2678 "True if SYMBOL is external in PACKAGE.
2679 If PACKAGE is not specified, the home package of SYMBOL is used."
2680 (and package
2681 (eq (nth-value 1 (find-symbol (symbol-name symbol) package))
2682 :external)))
2683
2684 (defun find-matching-packages (name matcher)
2685 "Return a list of package names matching NAME with MATCHER.
2686 MATCHER is a two-argument predicate."
2687 (let ((to-match (string-upcase name)))
2688 (remove-if-not (lambda (x) (funcall matcher to-match x))
2689 (mapcar (lambda (pkgname)
2690 (concatenate 'string pkgname ":"))
2691 (loop for package in (list-all-packages)
2692 collect (package-name package)
2693 append (package-nicknames package))))))
2694
2695 (defun parse-completion-arguments (string default-package-name)
2696 "Parse STRING as a symbol designator.
2697 Return these values:
2698 SYMBOL-NAME
2699 PACKAGE-NAME, or nil if the designator does not include an explicit package.
2700 PACKAGE, the package to complete in
2701 INTERNAL-P, if the symbol is qualified with `::'."
2702 (multiple-value-bind (name package-name internal-p)
2703 (tokenize-symbol string)
2704 (let ((package (carefully-find-package package-name default-package-name)))
2705 (values name package-name package internal-p))))
2706
2707 (defun carefully-find-package (name default-package-name)
2708 "Find the package with name NAME, or DEFAULT-PACKAGE-NAME, or the
2709 *buffer-package*. NAME and DEFAULT-PACKAGE-NAME can be nil."
2710 (let ((string (cond ((equal name "") "KEYWORD")
2711 (t (or name default-package-name)))))
2712 (if string
2713 (guess-package-from-string string nil)
2714 *buffer-package*)))
2715
2716 ;;;;; Format completion results
2717 ;;;
2718 ;;; We try to format results in the case as inputs. If you complete
2719 ;;; `FOO' then your result should include `FOOBAR' rather than
2720 ;;; `foobar'.
2721
2722 (defun format-completion-set (strings internal-p package-name)
2723 "Format a set of completion strings.
2724 Returns a list of completions with package qualifiers if needed."
2725 (mapcar (lambda (string)
2726 (format-completion-result string internal-p package-name))
2727 (sort strings #'string<)))
2728
2729 (defun format-completion-result (string internal-p package-name)
2730 (let ((prefix (cond (internal-p (format nil "~A::" package-name))
2731 (package-name (format nil "~A:" package-name))
2732 (t ""))))
2733 (values (concatenate 'string prefix string)
2734 (length prefix))))
2735
2736 (defun output-case-converter (input)
2737 "Return a function to case convert strings for output.
2738 INPUT is used to guess the preferred case."
2739 (ecase (readtable-case *readtable*)
2740 (:upcase (if (some #'lower-case-p input) #'string-downcase #'identity))
2741 (:invert (lambda (output)
2742 (multiple-value-bind (lower upper) (determine-case output)
2743 (cond ((and lower upper) output)
2744 (lower (string-upcase output))
2745 (upper (string-downcase output))
2746 (t output)))))
2747 (:downcase (if (some #'upper-case-p input) #'string-upcase #'identity))
2748 (:preserve #'identity)))
2749
2750 (defun determine-case (string)
2751 "Return two booleans LOWER and UPPER indicating whether STRING
2752 contains lower or upper case characters."
2753 (values (some #'lower-case-p string)
2754 (some #'upper-case-p string)))
2755
2756
2757 ;;;;; Compound-prefix matching
2758
2759 (defun compound-prefix-match (prefix target)
2760 "Return true if PREFIX is a compound-prefix of TARGET.
2761 Viewing each of PREFIX and TARGET as a series of substrings delimited
2762 by hyphens, if each substring of PREFIX is a prefix of the
2763 corresponding substring in TARGET then we call PREFIX a
2764 compound-prefix of TARGET.
2765
2766 Examples:
2767 \(compound-prefix-match \"foo\" \"foobar\") => t
2768 \(compound-prefix-match \"m--b\" \"multiple-value-bind\") => t
2769 \(compound-prefix-match \"m-v-c\" \"multiple-value-bind\") => NIL"
2770 (declare (type simple-string prefix target))
2771 (loop for ch across prefix
2772 with tpos = 0
2773 always (and (< tpos (length target))
2774 (if (char= ch #\-)
2775 (setf tpos (position #\- target :start tpos))
2776 (char= ch (aref target tpos))))
2777 do (incf tpos)))
2778
2779 (defun prefix-match-p (prefix string)
2780 "Return true if PREFIX is a prefix of STRING."
2781 (not (mismatch prefix string :end2 (min (length string) (length prefix)))))
2782
2783
2784 ;;;;; Extending the input string by completion
2785
2786 (defun longest-completion (completions)
2787 "Return the longest prefix for all COMPLETIONS.
2788 COMPLETIONS is a list of strings."
2789 (untokenize-completion
2790 (mapcar #'longest-common-prefix
2791 (transpose-lists (mapcar #'tokenize-completion completions)))))
2792
2793 (defun tokenize-completion (string)
2794 "Return all substrings of STRING delimited by #\-."
2795 (loop with end
2796 for start = 0 then (1+ end)
2797 until (> start (length string))
2798 do (setq end (or (position #\- string :start start) (length string)))
2799 collect (subseq string start end)))
2800
2801 (defun untokenize-completion (tokens)
2802 (format nil "~{~A~^-~}" tokens))
2803
2804 (defun longest-common-prefix (strings)
2805 "Return the longest string that is a common prefix of STRINGS."
2806 (if (null strings)
2807 ""
2808 (flet ((common-prefix (s1 s2)
2809 (let ((diff-pos (mismatch s1 s2)))
2810 (if diff-pos (subseq s1 0 diff-pos) s1))))
2811 (reduce #'common-prefix strings))))
2812
2813 (defun transpose-lists (lists)
2814 "Turn a list-of-lists on its side.
2815 If the rows are of unequal length, truncate uniformly to the shortest.
2816
2817 For example:
2818 \(transpose-lists '((ONE TWO THREE) (1 2)))
2819 => ((ONE 1) (TWO 2))"
2820 (cond ((null lists) '())
2821 ((some #'null lists) '())
2822 (t (cons (mapcar #'car lists)
2823 (transpose-lists (mapcar #'cdr lists))))))
2824
2825
2826 ;;;;; Completion Tests
2827
2828 (defpackage :swank-completion-test
2829 (:use))
2830
2831 (let ((*readtable* (copy-readtable *readtable*))
2832 (p (find-package :swank-completion-test)))
2833 (intern "foo" p)
2834 (intern "Foo" p)
2835 (intern "FOO" p)
2836 (setf (readtable-case *readtable*) :invert)
2837 (flet ((names (prefix)
2838 (sort (mapcar #'symbol-name
2839 (find-matching-symbols prefix p nil #'prefix-match-p))
2840 #'string<)))
2841 (assert (equal '("FOO") (names "f")))
2842 (assert (equal '("Foo" "foo") (names "F")))
2843 (assert (equal '("Foo") (names "Fo")))
2844 (assert (equal '("foo") (names "FO")))))
2845
2846 ;;;; Fuzzy completion
2847
2848 (defslimefun fuzzy-completions (string default-package-name &optional limit)
2849 "Return an (optionally limited to LIMIT best results) list of
2850 fuzzy completions for a symbol designator STRING. The list will
2851 be sorted by score, most likely match first.
2852
2853 The result is a list of completion objects, where a completion
2854 object is:
2855 (COMPLETED-STRING SCORE (&rest CHUNKS) FLAGS)
2856 where a CHUNK is a description of a matched string of characters:
2857 (OFFSET STRING)
2858 and FLAGS is a list of keywords describing properties of the symbol.
2859 For example, the top result for completing \"mvb\" in a package
2860 that uses COMMON-LISP would be something like:
2861 (\"multiple-value-bind\" 42.391666 ((0 \"mul\") (9 \"v\") (15 \"b\"))
2862 (:FBOUNDP :MACRO))
2863
2864 If STRING is package qualified the result list will also be
2865 qualified. If string is non-qualified the result strings are
2866 also not qualified and are considered relative to
2867 DEFAULT-PACKAGE-NAME.
2868
2869 Which symbols are candidates for matching depends on the symbol
2870 designator's format. The cases are as follows:
2871 FOO - Symbols accessible in the buffer package.
2872 PKG:FOO - Symbols external in package PKG.
2873 PKG::FOO - Symbols accessible in package PKG."
2874 (fuzzy-completion-set string default-package-name limit))
2875
2876 (defun convert-fuzzy-completion-result (result converter
2877 internal-p package-name)
2878 "Converts a result from the fuzzy completion core into
2879 something that emacs is expecting. Converts symbols to strings,
2880 fixes case issues, and adds information describing if the symbol
2881 is :bound, :fbound, a :class, a :macro, a :generic-function,
2882 a :special-operator, or a :package."
2883 (destructuring-bind (symbol-or-name score chunks) result
2884 (multiple-value-bind (name added-length)
2885 (format-completion-result
2886 (funcall converter
2887 (if (symbolp symbol-or-name)
2888 (symbol-name symbol-or-name)
2889 symbol-or-name))
2890 internal-p package-name)
2891 (list name score
2892 (mapcar
2893 #'(lambda (chunk)
2894 ;; fix up chunk positions to account for possible
2895 ;; added package identifier
2896 (list (+ added-length (first chunk))
2897 (second chunk)))
2898 chunks)
2899 (loop for flag in '(:boundp :fboundp :generic-function
2900 :class :macro :special-operator
2901 :package)
2902 if (if (symbolp symbol-or-name)
2903 (case flag
2904 (:boundp (boundp symbol-or-name))
2905 (:fboundp (fboundp symbol-or-name))
2906 (:class (find-class symbol-or-name nil))
2907 (:macro (macro-function symbol-or-name))
2908 (:special-operator
2909 (special-operator-p symbol-or-name))
2910 (:generic-function
2911 (typep (ignore-errors (fdefinition symbol-or-name))
2912 'generic-function)))
2913 (case flag
2914 (:package (stringp symbol-or-name)
2915 ;; KLUDGE: depends on internal
2916 ;; knowledge that packages are
2917 ;; brought up from the bowels of
2918 ;; the completion algorithm as
2919 ;; strings!
2920 )))
2921 collect flag)))))
2922
2923 (defun fuzzy-completion-set (string default-package-name &optional limit)
2924 "Prepares list of completion obajects, sorted by SCORE, of fuzzy
2925 completions of STRING in DEFAULT-PACKAGE-NAME. If LIMIT is set,
2926 only the top LIMIT results will be returned."
2927 (multiple-value-bind (name package-name package internal-p)
2928 (parse-completion-arguments string default-package-name)
2929 (let* ((symbols (and package
2930 (fuzzy-find-matching-symbols name
2931 package
2932 (and (not internal-p)
2933 package-name))))
2934 (packs (and (not package-name)
2935 (fuzzy-find-matching-packages name)))
2936 (converter (output-case-converter name))
2937 (results
2938 (sort (mapcar #'(lambda (result)
2939 (convert-fuzzy-completion-result
2940 result converter internal-p package-name))
2941 (nconc symbols packs))
2942 #'> :key #'second)))
2943 (when (and limit
2944 (> limit 0)
2945 (< limit (length results)))
2946 (setf (cdr (nthcdr (1- limit) results)) nil))
2947 results)))
2948
2949 (defun fuzzy-find-matching-symbols (string package external)
2950 "Return a list of symbols in PACKAGE matching STRING using the
2951 fuzzy completion algorithm. If EXTERNAL is true, only external
2952 symbols are returned."
2953 (let ((completions '())
2954 (converter (output-case-converter string)))
2955 (flet ((symbol-match (symbol)
2956 (and (or (not external)
2957 (symbol-external-p symbol package))
2958 (compute-highest-scoring-completion
2959 string (funcall converter (symbol-name symbol)) #'char=))))
2960 (do-symbols (symbol package)
2961 (if (string= "" string)
2962 (when (or (and external (symbol-external-p symbol package))
2963 (not external))
2964 (push (list symbol 0.0 (list (list 0 ""))) completions))
2965 (multiple-value-bind (result score) (symbol-match symbol)
2966 (when result
2967 (push (list symbol score result) completions))))))
2968 (remove-duplicates completions :key #'first)))
2969
2970 (defun fuzzy-find-matching-packages (name)
2971 "Return a list of package names matching NAME using the fuzzy
2972 completion algorithm."
2973 (let ((converter (output-case-converter name)))
2974 (loop for package in (list-all-packages)
2975 for package-name = (concatenate 'string
2976 (funcall converter
2977 (package-name package))
2978 ":")
2979 for (result score) = (multiple-value-list
2980 (compute-highest-scoring-completion
2981 name package-name #'char=))
2982 if result collect (list package-name score result))))
2983
2984 (defslimefun fuzzy-completion-selected (original-string completion)
2985 "This function is called by Slime when a fuzzy completion is
2986 selected by the user. It is for future expansion to make
2987 testing, say, a machine learning algorithm for completion scoring
2988 easier.
2989
2990 ORIGINAL-STRING is the string the user completed from, and
2991 COMPLETION is the completion object (see docstring for
2992 SWANK:FUZZY-COMPLETIONS) corresponding to the completion that the
2993 user selected."
2994 (declare (ignore original-string completion))
2995 nil)
2996
2997 ;;;;; Fuzzy completion core
2998
2999 (defparameter *fuzzy-recursion-soft-limit* 30
3000 "This is a soft limit for recursion in
3001 RECURSIVELY-COMPUTE-MOST-COMPLETIONS. Without this limit,
3002 completing a string such as \"ZZZZZZ\" with a symbol named
3003 \"ZZZZZZZZZZZZZZZZZZZZZZZ\" will result in explosive recursion to
3004 find all the ways it can match.
3005
3006 Most natural language searches and symbols do not have this
3007 problem -- this is only here as a safeguard.")
3008
3009 (defun compute-highest-scoring-completion (short full test)
3010 "Finds the highest scoring way to complete the abbreviation
3011 SHORT onto the string FULL, using TEST as a equality function for
3012 letters. Returns two values: The first being the completion
3013 chunks of the high scorer, and the second being the score."
3014 (let* ((scored-results
3015 (mapcar #'(lambda (result)
3016 (cons (score-completion result short full) result))
3017 (compute-most-completions short full test)))
3018 (winner (first (sort scored-results #'> :key #'first))))
3019 (values (rest winner) (first winner))))
3020
3021 (defun compute-most-completions (short full test)
3022 "Finds most possible ways to complete FULL with the letters in SHORT.
3023 Calls RECURSIVELY-COMPUTE-MOST-COMPLETIONS recursively. Returns
3024 a list of (&rest CHUNKS), where each CHUNKS is a description of
3025 how a completion matches."
3026 (let ((*all-chunks* nil))
3027 (declare (special *all-chunks*))
3028 (recursively-compute-most-completions short full test 0 0 nil nil nil t)
3029 *all-chunks*))
3030
3031 (defun recursively-compute-most-completions
3032 (short full test
3033 short-index initial-full-index
3034 chunks current-chunk current-chunk-pos
3035 recurse-p)
3036 "Recursively (if RECURSE-P is true) find /most/ possible ways
3037 to fuzzily map the letters in SHORT onto FULL, with TEST being a
3038 function to determine if two letters match.
3039
3040 A chunk is a list of elements that have matched consecutively.
3041 When consecutive matches stop, it is coerced into a string,
3042 paired with the starting position of the chunk, and pushed onto
3043 CHUNKS.
3044
3045 Whenever a letter matches, if RECURSE-P is true,
3046 RECURSIVELY-COMPUTE-MOST-COMPLETIONS calls itself with a position
3047 one index ahead, to find other possibly higher scoring
3048 possibilities. If there are less than
3049 *FUZZY-RECURSION-SOFT-LIMIT* results in *ALL-CHUNKS* currently,
3050 this call will also recurse.
3051
3052 Once a word has been completely matched, the chunks are pushed
3053 onto the special variable *ALL-CHUNKS* and the function returns."
3054 (declare (special *all-chunks*))
3055 (flet ((short-cur ()
3056 "Returns the next letter from the abbreviation, or NIL
3057 if all have been used."
3058 (if (= short-index (length short))
3059 nil
3060 (aref short short-index)))
3061 (add-to-chunk (char pos)
3062 "Adds the CHAR at POS in FULL to the current chunk,
3063 marking the start position if it is empty."
3064 (unless current-chunk
3065 (setf current-chunk-pos pos))
3066 (push char current-chunk))
3067 (collect-chunk ()
3068 "Collects the current chunk to CHUNKS and prepares for
3069 a new chunk."
3070 (when current-chunk
3071 (push (list current-chunk-pos
3072 (coerce (reverse current-chunk) 'string)) chunks)
3073 (setf current-chunk nil
3074 current-chunk-pos nil))))
3075 ;; If there's an outstanding chunk coming in collect it. Since
3076 ;; we're recursively called on skipping an input character, the
3077 ;; chunk can't possibly continue on.
3078 (when current-chunk (collect-chunk))
3079 (do ((pos initial-full-index (1+ pos)))
3080 ((= pos (length full)))
3081 (let ((cur-char (aref full pos)))
3082 (if (and (short-cur)
3083 (funcall test cur-char (short-cur)))
3084 (progn
3085 (when recurse-p
3086 ;; Try other possibilities, limiting insanely deep
3087 ;; recursion somewhat.
3088 (recursively-compute-most-completions
3089 short full test short-index (1+ pos)
3090 chunks current-chunk current-chunk-pos
3091 (not (> (length *all-chunks*)
3092 *fuzzy-recursion-soft-limit*))))
3093 (incf short-index)
3094 (add-to-chunk cur-char pos))
3095 (collect-chunk))))
3096 (collect-chunk)
3097 ;; If we've exhausted the short characters we have a match.
3098 (if (short-cur)
3099 nil
3100 (let ((rev-chunks (reverse chunks)))
3101 (push rev-chunks *all-chunks*)
3102 rev-chunks))))
3103
3104 ;;;;; Fuzzy completion scoring
3105
3106 (defparameter *fuzzy-completion-symbol-prefixes* "*+-%&?<"
3107 "Letters that are likely to be at the beginning of a symbol.
3108 Letters found after one of these prefixes will be scored as if
3109 they were at the beginning of ths symbol.")
3110 (defparameter *fuzzy-completion-symbol-suffixes* "*+->"
3111 "Letters that are likely to be at the end of a symbol.
3112 Letters found before one of these suffixes will be scored as if
3113 they were at the end of the symbol.")
3114 (defparameter *fuzzy-completion-word-separators* "-/."
3115 "Letters that separate different words in symbols. Letters
3116 after one of these symbols will be scores more highly than other
3117 letters.")
3118
3119 (defun score-completion (completion short full)
3120 "Scores the completion chunks COMPLETION as a completion from
3121 the abbreviation SHORT to the full string FULL. COMPLETION is a
3122 list like:
3123 ((0 \"mul\") (9 \"v\") (15 \"b\"))
3124 Which, if SHORT were \"mulvb\" and full were \"multiple-value-bind\",
3125 would indicate that it completed as such (completed letters
3126 capitalized):
3127 MULtiple-Value-Bind
3128
3129 Letters are given scores based on their position in the string.
3130 Letters at the beginning of a string or after a prefix letter at
3131 the beginning of a string are scored highest. Letters after a
3132 word separator such as #\- are scored next highest. Letters at
3133 the end of a string or before a suffix letter at the end of a
3134 string are scored medium, and letters anywhere else are scored
3135 low.
3136
3137 If a letter is directly after another matched letter, and its
3138 intrinsic value in that position is less than a percentage of the
3139 previous letter's value, it will use that percentage instead.
3140
3141 Finally, a small scaling factor is applied to favor shorter
3142 matches, all other things being equal."
3143 (labels ((at-beginning-p (pos)
3144 (= pos 0))
3145 (after-prefix-p (pos)
3146 (and (= pos 1)
3147 (find (aref full 0) *fuzzy-completion-symbol-prefixes*)))
3148 (word-separator-p (pos)
3149 (find (aref full pos) *fuzzy-completion-word-separators*))
3150 (after-word-separator-p (pos)
3151 (find (aref full (1- pos)) *fuzzy-completion-word-separators*))
3152 (at-end-p (pos)
3153 (= pos (1- (length full))))
3154 (before-suffix-p (pos)
3155 (and (= pos (- (length full) 2))
3156 (find (aref full (1- (length full)))
3157 *fuzzy-completion-symbol-suffixes*)))
3158 (score-or-percentage-of-previous (base-score pos chunk-pos)
3159 (if (zerop chunk-pos)
3160 base-score
3161 (max base-score
3162 (* (score-char (1- pos) (1- chunk-pos)) 0.85))))
3163 (score-char (pos chunk-pos)
3164 (score-or-percentage-of-previous
3165 (cond ((at-beginning-p pos) 10)
3166 ((after-prefix-p pos) 10)
3167 ((word-separator-p pos) 1)
3168 ((after-word-separator-p pos) 8)
3169 ((at-end-p pos) 6)
3170 ((before-suffix-p pos) 6)
3171 (t 1))
3172 pos chunk-pos))
3173 (score-chunk (chunk)
3174 (loop for chunk-pos below (length (second chunk))
3175 for pos from (first chunk)
3176 summing (score-char pos chunk-pos))))
3177 (let* ((chunk-scores (mapcar #'score-chunk completion))
3178 (length-score (/ 10.0 (1+ (- (length full) (length short))))))
3179 (values
3180 (+ (reduce #'+ chunk-scores) length-score)
3181 (list (mapcar #'list chunk-scores completion) length-score)))))
3182
3183 (defun highlight-completion (completion full)
3184 "Given a chunk definition COMPLETION and the string FULL,
3185 HIGHLIGHT-COMPLETION will create a string that demonstrates where
3186 the completion matched in the string. Matches will be
3187 capitalized, while the rest of the string will be lower-case."
3188 (let ((highlit (nstring-downcase (copy-seq full))))
3189 (dolist (chunk completion)
3190 (setf highlit (nstring-upcase highlit
3191 :start (first chunk)
3192 :end (+ (first chunk)
3193 (length (second chunk))))))
3194 highlit))
3195
3196 (defun format-fuzzy-completions (winners)
3197 "Given a list of completion objects such as on returned by
3198 FUZZY-COMPLETIONS, format the list into user-readable output."
3199 (let ((max-len
3200 (loop for winner in winners maximizing (length (first winner)))))
3201 (loop for (sym score result) in winners do
3202 (format t "~&~VA score ~8,2F ~A"
3203 max-len (highlight-completion result sym) score result))))
3204
3205
3206 ;;;; Documentation
3207
3208 (defslimefun apropos-list-for-emacs (name &optional external-only
3209 case-sensitive package)
3210 "Make an apropos search for Emacs.
3211 The result is a list of property lists."
3212 (let ((package (if package
3213 (or (find-package (string-to-package-designator package))
3214 (error "No such package: ~S" package)))))
3215 (mapcan (listify #'briefly-describe-symbol-for-emacs)
3216 (sort (remove-duplicates
3217 (apropos-symbols name external-only case-sensitive package))
3218 #'present-symbol-before-p))))
3219
3220 (defun string-to-package-designator (string)
3221 "Return a package designator made from STRING.
3222 Uses READ to case-convert STRING."
3223 (let ((*package* *swank-io-package*))
3224 (read-from-string string)))
3225
3226 (defun briefly-describe-symbol-for-emacs (symbol)
3227 "Return a property list describing SYMBOL.
3228 Like `describe-symbol-for-emacs' but with at most one line per item."
3229 (flet ((first-line (string)
3230 (let ((pos (position #\newline string)))
3231 (if (null pos) string (subseq string 0 pos)))))
3232 (let ((desc (map-if #'stringp #'first-line
3233 (describe-symbol-for-emacs symbol))))
3234 (if desc
3235 (list* :designator (to-string symbol) desc)))))
3236
3237 (defun map-if (test fn &rest lists)
3238 "Like (mapcar FN . LISTS) but only call FN on objects satisfying TEST.
3239 Example:
3240 \(map-if #'oddp #'- '(1 2 3 4 5)) => (-1 2 -3 4 -5)"
3241 (declare (type function test fn))
3242 (apply #'mapcar
3243 (lambda (x) (if (funcall test x) (funcall fn x) x))
3244 lists))
3245
3246 (defun listify (f)
3247 "Return a function like F, but which returns any non-null value
3248 wrapped in a list."
3249 (declare (type function f))
3250 (lambda (x)
3251 (let ((y (funcall f x)))
3252 (and y (list y)))))
3253
3254 (defun present-symbol-before-p (x y)
3255 "Return true if X belongs before Y in a printed summary of symbols.
3256 Sorted alphabetically by package name and then symbol name, except
3257 that symbols accessible in the current package go first."
3258 (declare (type symbol x y))
3259 (flet ((accessible (s)
3260 ;; Test breaks on NIL for package that does not inherit it
3261 (eq (find-symbol (symbol-name s) *buffer-package*) s)))
3262 (let ((ax (accessible x)) (ay (accessible y)))
3263 (cond ((and ax ay) (string< (symbol-name x) (symbol-name y)))
3264 (ax t)
3265 (ay nil)
3266 (t (let ((px (symbol-package x)) (py (symbol-package y)))
3267 (if (eq px py)
3268 (string< (symbol-name x) (symbol-name y))
3269 (string< (package-name px) (package-name py)))))))))
3270
3271 (let ((regex-hash (make-hash-table :test #'equal)))
3272 (defun compiled-regex (regex-string)
3273 (or (gethash regex-string regex-hash)
3274 (setf (gethash regex-string regex-hash)
3275 (if (zerop (length regex-string))
3276 (lambda (s) (check-type s string) t)
3277 (compile nil (slime-nregex:regex-compile regex-string)))))))
3278
3279 (defun apropos-matcher (string case-sensitive package external-only)
3280 (let* ((case-modifier (if case-sensitive #'string #'string-upcase))
3281 (regex (compiled-regex (funcall case-modifier string))))
3282 (lambda (symbol)
3283 (and (not (keywordp symbol))
3284 (if package (eq (symbol-package symbol) package) t)
3285 (if external-only (symbol-external-p symbol) t)
3286 (funcall regex (funcall case-modifier symbol))))))
3287
3288 (defun apropos-symbols (string external-only case-sensitive package)
3289 (let ((result '())
3290 (matchp (apropos-matcher string case-sensitive package external-only)))
3291 (with-package-iterator (next (or package (list-all-packages))
3292 :external :internal)
3293 (loop
3294 (multiple-value-bind (morep symbol) (next)
3295 (cond ((not morep)
3296 (return))
3297 ((funcall matchp symbol)
3298 (push symbol result))))))
3299 result))
3300
3301 (defun call-with-describe-settings (fn)
3302 (let ((*print-readably* nil))
3303 (funcall fn)))
3304
3305 (defmacro with-describe-settings ((&rest _) &body body)
3306 (declare (ignore _))
3307 `(call-with-describe-settings (lambda () ,@body)))
3308
3309 (defun describe-to-string (object)
3310 (with-describe-settings ()
3311 (with-output-to-string (*standard-output*)
3312 (describe object))))
3313
3314 (defslimefun describe-symbol (symbol-name)
3315 (with-buffer-syntax ()
3316 (describe-to-string (parse-symbol-or-lose symbol-name))))
3317
3318 (defslimefun describe-function (name)
3319 (with-buffer-syntax ()
3320 (let ((symbol (parse-symbol-or-lose name)))
3321 (describe-to-string (or (macro-function symbol)
3322 (symbol-function symbol))))))
3323
3324 (defslimefun describe-definition-for-emacs (name kind)
3325 (with-buffer-syntax ()
3326 (with-describe-settings ()
3327 (with-output-to-string (*standard-output*)
3328 (describe-definition (parse-symbol-or-lose name) kind)))))
3329
3330 (defslimefun documentation-symbol (symbol-name &optional default)
3331 (with-buffer-syntax ()
3332 (multiple-value-bind (sym foundp) (parse-symbol symbol-name)
3333 (if foundp
3334 (let ((vdoc (documentation sym 'variable))
3335 (fdoc (documentation sym 'function)))
3336 (or (and (or vdoc fdoc)
3337 (concatenate 'string
3338 fdoc
3339 (and vdoc fdoc '(#\Newline #\Newline))
3340 vdoc))
3341 default))
3342 default))))
3343
3344
3345 ;;;; Package Commands
3346
3347 (defslimefun list-all-package-names (&optional include-nicknames)
3348 "Return a list of all package names.
3349 Include the nicknames if INCLUDE-NICKNAMES is true."
3350 (loop for package in (list-all-packages)
3351 collect (package-name package)
3352 when include-nicknames append (package-nicknames package)))
3353
3354
3355 ;;;; Tracing
3356
3357 ;; Use eval for the sake of portability...
3358 (defun tracedp (fspec)
3359 (member fspec (eval '(trace))))
3360
3361 (defslimefun swank-toggle-trace (spec-string)
3362 (let ((spec (from-string spec-string)))
3363 (cond ((consp spec) ; handle complicated cases in the backend
3364 (toggle-trace spec))
3365 ((tracedp spec)
3366 (eval `(untrace ,spec))
3367 (format nil "~S is now untraced." spec))
3368 (t
3369 (eval `(trace ,spec))
3370 (format nil "~S is now traced." spec)))))
3371
3372 (defslimefun untrace-all ()
3373 (untrace))
3374
3375
3376 ;;;; Undefing
3377
3378 (defslimefun undefine-function (fname-string)
3379 (let ((fname (from-string fname-string)))
3380 (format nil "~S" (fmakunbound fname))))
3381
3382
3383 ;;;; Profiling
3384
3385 (defun profiledp (fspec)
3386 (member fspec (profiled-functions)))
3387
3388 (defslimefun toggle-profile-fdefinition (fname-string)
3389 (let ((fname (from-string fname-string)))
3390 (cond ((profiledp fname)
3391 (unprofile fname)
3392 (format nil "~S is now unprofiled." fname))
3393 (t
3394 (profile fname)
3395 (format nil "~S is now profiled." fname)))))
3396
3397
3398 ;;;; Source Locations
3399
3400 (defslimefun find-definitions-for-emacs (name)
3401 "Return a list ((DSPEC LOCATION) ...) of definitions for NAME.
3402 DSPEC is a string and LOCATION a source location. NAME is a string."
3403 (multiple-value-bind (sexp error)
3404 (ignore-errors (values (from-string name)))
3405 (cond (error '())
3406 (t (loop for (dspec loc) in (find-definitions sexp)
3407 collect (list (to-string dspec) loc))))))
3408
3409 (defun alistify (list key test)
3410 "Partition the elements of LIST into an alist. KEY extracts the key
3411 from an element and TEST is used to compare keys."
3412 (declare (type function key))
3413 (let ((alist '()))
3414 (dolist (e list)
3415 (let* ((k (funcall key e))
3416 (probe (assoc k alist :test test)))
3417 (if probe
3418 (push e (cdr probe))
3419 (push (cons k (list e)) alist))))
3420 alist))
3421
3422 (defun location-position< (pos1 pos2)
3423 (cond ((and (position-p pos1) (position-p pos2))
3424 (< (position-pos pos1)
3425 (position-pos pos2)))
3426 (t nil)))
3427
3428 (defun partition (list test key)
3429 (declare (type function test key))
3430 (loop for e in list
3431 if (funcall test (funcall key e)) collect e into yes
3432 else collect e into no
3433 finally (return (values yes no))))
3434
3435 (defstruct (xref (:conc-name xref.)
3436 (:type list))
3437 dspec location)
3438
3439 (defun location-valid-p (location)
3440 (eq (car location) :location))
3441
3442 (defun xref-buffer (xref)
3443 (location-buffer (xref.location xref)))
3444
3445 (defun xref-position (xref)
3446 (location-buffer (xref.location xref)))
3447
3448 (defun group-xrefs (xrefs)
3449 "Group XREFS, a list of the form ((DSPEC LOCATION) ...) by location.
3450 The result is a list of the form ((LOCATION . ((DSPEC . LOCATION) ...)) ...)."
3451 (multiple-value-bind (resolved errors)
3452 (partition xrefs #'location-valid-p #'xref.location)
3453 (let ((alist (alistify resolved #'xref-buffer #'equal)))
3454 (append
3455 (loop for (buffer . list) in alist
3456 collect (cons (second buffer)
3457 (mapcar (lambda (xref)
3458 (cons (to-string (xref.dspec xref))
3459 (xref.location xref)))
3460 (sort list #'location-position<
3461 :key #'xref-position))))
3462 (if errors
3463 (list (cons "Unresolved"
3464 (mapcar (lambda (xref)
3465 (cons (to-string (xref.dspec xref))
3466 (xref.location xref)))
3467 errors))))))))
3468
3469 (defslimefun xref (type symbol-name)
3470 (let ((symbol (parse-symbol-or-lose symbol-name *buffer-package*)))
3471 (group-xrefs
3472 (ecase type
3473 (:calls (who-calls symbol))
3474 (:calls-who (calls-who symbol))
3475 (:references (who-references symbol))
3476 (:binds (who-binds symbol))
3477 (:sets (who-sets symbol))
3478 (:macroexpands (who-macroexpands symbol))
3479 (:specializes (who-specializes symbol))
3480 (:callers (list-callers symbol))
3481 (:callees (list-callees symbol))))))
3482
3483
3484 ;;;; Inspecting
3485
3486 (defun common-seperated-spec (list &optional (callback (lambda (v)
3487 `(:value ,v))))
3488 (butlast
3489 (loop
3490 for i in list
3491 collect (funcall callback i)
3492 collect ", ")))
3493
3494 (defun inspector-princ (list)
3495 "Like princ-to-string, but don't rewrite (function foo) as #'foo.
3496 Do NOT pass circular lists to this function."
3497 (let ((*print-pprint-dispatch* (copy-pprint-dispatch)))
3498 (set-pprint-dispatch '(cons (member function)) nil)
3499 (princ-to-string list)))
3500
3501 (defmethod inspect-for-emacs ((object cons) inspector)
3502 (declare (ignore inspector))
3503 (if (consp (cdr object))
3504 (inspect-for-emacs-list object)
3505 (inspect-for-emacs-simple-cons object)))
3506
3507 (defun inspect-for-emacs-simple-cons (cons)
3508 (values "A cons cell."
3509 (label-value-line*
3510 ('car (car cons))
3511 ('cdr (cdr cons)))))
3512
3513 (defun inspect-for-emacs-list (list)
3514 (let ((maxlen 40))
3515 (multiple-value-bind (length tail) (safe-length list)
3516 (flet ((frob (title list)
3517 (let ((lines
3518 (do ((i 0 (1+ i))
3519 (l list (cdr l))
3520 (a '() (cons (label-value-line i (car l)) a)))
3521 ((not (consp l))
3522 (let ((a (if (null l)
3523 a
3524 (cons (label-value-line :tail l) a))))
3525 (reduce #'append (reverse a) :from-end t))))))
3526 (values title (append '("Elements:" (:newline)) lines)))))
3527
3528 (cond ((not length) ; circular
3529 (frob "A circular list."
3530 (cons (car list)
3531 (ldiff (cdr list) list))))
3532 ((and (<= length maxlen) (not tail))
3533 (frob "A proper list." list))
3534 (tail
3535 (frob "An improper list." list))
3536 (t
3537 (frob "A proper list." list)))))))
3538
3539 ;; (inspect-for-emacs-list '#1=(a #1# . #1# ))
3540
3541 (defun safe-length (list)
3542 "Similar to `list-length', but avoid errors on improper lists.
3543 Return two values: the length of the list and the last cdr.
3544 NIL is returned if the list is circular."
3545 (do ((n 0 (+ n 2)) ;Counter.
3546 (fast list (cddr fast)) ;Fast pointer: leaps by 2.
3547 (slow list (cdr slow))) ;Slow pointer: leaps by 1.
3548 (nil)
3549 (cond ((null fast) (return (values n nil)))
3550 ((not (consp fast)) (return (values n fast)))
3551 ((null (cdr fast)) (return (values (1+ n) (cdr fast))))
3552 ((and (eq fast slow) (> n 0)) (return nil))
3553 ((not (consp (cdr fast))) (return (values (1+ n) (cdr fast)))))))
3554
3555 (defvar *slime-inspect-contents-limit* nil "How many elements of
3556 a hash table or array to show by default. If table has more than
3557 this then offer actions to view more. Set to nil for no limit." )
3558
3559 (defmethod inspect-for-emacs ((ht hash-table) inspector)
3560 (declare (ignore inspector))
3561 (values (prin1-to-string ht)
3562 (append
3563 (label-value-line*
3564 ("Count" (hash-table-count ht))
3565 ("Size" (hash-table-size ht))
3566 ("Test" (hash-table-test ht))
3567 ("Rehash size" (hash-table-rehash-size ht))
3568 ("Rehash threshold" (hash-table-rehash-threshold ht)))
3569 '("Contents: " (:newline))
3570 (if (and *slime-inspect-contents-limit*
3571 (>= (hash-table-count ht) *slime-inspect-contents-limit*))
3572 (inspect-bigger-piece-actions ht (hash-table-count ht))
3573 nil)
3574 (loop for key being the hash-keys of ht
3575 for value being the hash-values of ht
3576 repeat (or *slime-inspect-contents-limit* most-positive-fixnum)
3577 append `((:value ,key) " = " (:value ,value) (:newline))
3578 )
3579
3580 )))
3581
3582 (defmethod inspect-bigger-piece-actions (thing size)
3583 (append
3584 (if (> size *slime-inspect-contents-limit*)
3585 (list (inspect-show-more-action thing)
3586 '(:newline))
3587 nil)
3588 (list (inspect-whole-thing-action thing size)
3589 '(:newline))))
3590
3591 (defmethod inspect-whole-thing-action (thing size)
3592 `(:action ,(format nil "Inspect all ~a elements."
3593 size)
3594 ,(lambda()
3595 (let ((*slime-inspect-contents-limit* nil))
3596 (values
3597 (swank::inspect-object thing)
3598 :replace)
3599 ))))
3600
3601 (defmethod inspect-show-more-action (thing)
3602 `(:action ,(format nil "~a elements shown. Prompt for how many to inspect..."
3603 *slime-inspect-contents-limit* )
3604 ,(lambda()
3605 (let ((*slime-inspect-contents-limit*
3606 (progn (format t "How many elements should be shown? ") (read))))
3607 (values
3608 (swank::inspect-object thing)
3609 :replace)
3610 ))
3611 ))
3612
3613 (defmethod inspect-for-emacs ((array array) inspector)
3614 (declare (ignore inspector))
3615 (values "An array."
3616 (append
3617 (label-value-line*
3618 ("Dimensions" (array-dimensions array))
3619 ("Its element type is" (array-element-type array))
3620 ("Total size" (array-total-size array))
3621 ("Adjustable" (adjustable-array-p array)))
3622 (when (array-has-fill-pointer-p array)
3623 (label-value-line "Fill pointer" (fill-pointer array)))
3624 '("Contents:" (:newline))
3625 (if (and *slime-inspect-contents-limit*
3626 (>= (array-total-size array) *slime-inspect-contents-limit*))
3627 (inspect-bigger-piece-actions array (length array))
3628 nil)
3629 (loop for i below (or *slime-inspect-contents-limit* (array-total-size array))
3630 append (label-value-line i (row-major-aref array i))))))
3631
3632 (defmethod inspect-for-emacs ((char character) inspector)
3633 (declare (ignore inspector))
3634 (values "A character."
3635 (append
3636 (label-value-line*
3637 ("Char code" (char-code char))
3638 ("Lower cased" (char-downcase char))
3639 ("Upper cased" (char-upcase char)))
3640 (if (get-macro-character char)
3641 `("In the current readtable ("
3642 (:value ,*readtable*) ") it is a macro character: "
3643 (:value ,(get-macro-character char)))))))
3644
3645 (defun docstring-ispec (label object kind)
3646 "Return a inspector spec if OBJECT has a docstring of of kind KIND."
3647 (let ((docstring (documentation object kind)))
3648 (cond ((not docstring) nil)
3649 ((< (+ (length label) (length docstring))
3650 75)
3651 (list label ": " docstring '(:newline)))
3652 (t
3653 (list label ": " '(:newline) " " docstring '(:newline))))))
3654
3655 (defmethod inspect-for-emacs ((symbol symbol) inspector)
3656 (declare (ignore inspector))
3657 (let ((package (symbol-package symbol)))
3658 (multiple-value-bind (_symbol status)
3659 (and package (find-symbol (string symbol) package))
3660 (declare (ignore _symbol))
3661 (values
3662 "A symbol."
3663 (append
3664 (label-value-line "Its name is" (symbol-name symbol))
3665 ;;
3666 ;; Value
3667 (cond ((boundp symbol)
3668 (label-value-line (if (constantp symbol)
3669 "It is a constant of value"
3670 "It is a global variable bound to")
3671 (symbol-value symbol)))
3672 (t '("It is unbound." (:newline))))
3673 (docstring-ispec "Documentation" symbol 'variable)
3674 (multiple-value-bind (expansion definedp) (macroexpand symbol)
3675 (if definedp
3676 (label-value-line "It is a symbol macro with expansion"
3677 expansion)))
3678 ;;
3679 ;; Function
3680 (if (fboundp symbol)
3681 (append (if (macro-function symbol)
3682 `("It a macro with macro-function: "
3683 (:value ,(macro-function symbol)))
3684 `("It is a function: "
3685 (:value ,(symbol-function symbol))))
3686 `(" " (:action "[make funbound]"
3687 ,(lambda () (fmakunbound symbol))))
3688 `((:newline)))
3689 `("It has no function value." (:newline)))
3690 (docstring-ispec "Function Documentation" symbol 'function)
3691 (if (compiler-macro-function symbol)
3692 (label-value-line "It also names the compiler macro"
3693 (compiler-macro-function symbol)))
3694 (docstring-ispec "Compiler Macro Documentation"
3695 symbol 'compiler-macro)
3696 ;;
3697 ;; Package
3698 (if package
3699 `("It is " ,(string-downcase (string status))
3700 " to the package: "
3701 (:value ,package ,(package-name package))
3702 ,@(if (eq :internal status)
3703 `(" "
3704 (:action "[export it]"
3705 ,(lambda () (export symbol package)))))
3706 " "
3707 (:action "[unintern it]"
3708 ,(lambda () (unintern symbol package)))
3709 (:newline))
3710 '("It is a non-interned symbol." (:newline)))
3711 ;;
3712 ;; Plist
3713 (label-value-line "Property list" (symbol-plist symbol))
3714 ;;
3715 ;; Class
3716 (if (find-class symbol nil)
3717 `("It names the class "
3718 (:value ,(find-class symbol) ,(string symbol))
3719 " "
3720 (:action "[remove]"
3721 ,(lambda () (setf (find-class symbol) nil)))
3722 (:newline)))
3723 ;;
3724 ;; More package
3725 (if (find-package symbol)
3726 (label-value-line "It names the package" (find-package symbol)))
3727 )))))
3728
3729 (defmethod inspect-for-emacs ((f function) inspector)
3730 (declare (ignore inspector))
3731 (values "A function."
3732 (append
3733 (label-value-line "Name" (function-name f))
3734 `("Its argument list is: "
3735 ,(inspector-princ (arglist f)) (:newline))
3736 (docstring-ispec "Documentation" f t)
3737 (if (function-lambda-expression f)
3738 (label-value-line "Lambda Expression"
3739 (function-lambda-expression f))))))
3740
3741 (defun method-specializers-for-inspect (method)
3742 "Return a \"pretty\" list of the method's specializers. Normal
3743 specializers are replaced by the name of the class, eql
3744 specializers are replaced by `(eql ,object)."
3745 (mapcar (lambda (spec)
3746 (typecase spec
3747 (swank-mop:eql-specializer
3748 `(eql ,(swank-mop:eql-specializer-object spec)))
3749 (t (swank-mop:class-name spec))))
3750 (swank-mop:method-specializers method)))
3751
3752 (defun method-for-inspect-value (method)
3753 "Returns a \"pretty\" list describing METHOD. The first element
3754 of the list is the name of generic-function method is
3755 specialiazed on, the second element is the method qualifiers,
3756 the rest of the list is the method's specialiazers (as per
3757 method-specializers-for-inspect)."
3758 (append (list (swank-mop:generic-function-name
3759 (swank-mop:method-generic-function method)))
3760 (swank-mop:method-qualifiers method)
3761 (method-specializers-for-inspect method)))
3762
3763 (defmethod inspect-for-emacs ((o standard-object) inspector)
3764 (declare (ignore inspector))
3765 (let ((c (class-of o)))
3766 (values "An object."
3767 `("Class: " (:value ,c) (:newline)
3768 "Slots:" (:newline)
3769 ,@(loop for slotd in (swank-mop:class-slots c)
3770 for name = (swank-mop:slot-definition-name slotd)
3771 collect `(:value ,slotd ,(string name))
3772 collect " = "
3773 collect (if (swank-mop:slot-boundp-using-class c o slotd)
3774 `(:value ,(swank-mop:slot-value-using-class
3775 c o slotd))
3776 "#<unbound>")
3777 collect '(:newline))))))
3778
3779 (defvar *gf-method-getter* 'methods-by-applicability
3780 "This function is called to get the methods of a generic function.
3781 The default returns the method sorted by applicability.
3782 See `methods-by-applicability'.")
3783
3784 (defun specializer< (specializer1 specializer2)
3785 "Return true if SPECIALIZER1 is more specific than SPECIALIZER2."
3786 (let ((s1 specializer1) (s2 specializer2) )
3787 (cond ((typep s1 'swank-mop:eql-specializer)
3788 (not (typep s2 'swank-mop:eql-specializer)))
3789 (t
3790 (flet ((cpl (class)
3791 (and (swank-mop:class-finalized-p class)
3792 (swank-mop:class-precedence-list class))))
3793 (member s2 (cpl s1)))))))
3794
3795 (defun methods-by-applicability (gf)
3796 "Return methods ordered by most specific argument types.
3797
3798 `method-specializer<' is used for sorting."
3799 ;; FIXME: argument-precedence-order and qualifiers are ignored.
3800 (let ((methods (copy-list (swank-mop:generic-function-methods gf))))
3801 (labels ((method< (meth1 meth2)
3802 (loop for s1 in (swank-mop:method-specializers meth1)
3803 for s2 in (swank-mop:method-specializers meth2)
3804 do (cond ((specializer< s2 s1) (return nil))
3805 ((specializer< s1 s2) (return t))))))
3806 (stable-sort methods #'method<))))
3807
3808 (defun abbrev-doc (doc &optional (maxlen 80))
3809 "Return the first sentence of DOC, but not more than MAXLAN characters."
3810 (subseq doc 0 (min (1+ (or (position #\. doc) (1- maxlen)))
3811 maxlen
3812 (length doc))))
3813
3814 (defun all-slots-for-inspector (object)
3815 (append (list "------------------------------" '(:newline)
3816 "All Slots:" '(:newline))
3817 (loop
3818 with direct-slots = (swank-mop:class-direct-slots (class-of object))
3819 for slot in (swank-mop:class-slots (class-of object))
3820 for slot-def = (or (find-if (lambda (a)
3821 ;; find the direct slot
3822 ;; with the same name
3823 ;; as SLOT (an
3824 ;; effective slot).
3825 (eql (swank-mop:slot-definition-name a)
3826 (swank-mop:slot-definition-name slot)))
3827 direct-slots)
3828 slot)
3829 collect `(:value ,slot-def ,(inspector-princ (swank-mop:slot-definition-name slot-def)))
3830 collect " = "
3831 if (slot-boundp object (swank-mop:slot-definition-name slot-def))
3832 collect `(:value ,(slot-value object (swank-mop:slot-definition-name slot-def)))
3833 else
3834 collect "#<unbound>"
3835 collect '(:newline))))
3836
3837 (defmethod inspect-for-emacs ((gf standard-generic-function) inspector)
3838 (declare (ignore inspector))
3839 (flet ((lv (label value) (label-value-line label value)))
3840 (values
3841 "A generic function."
3842 (append
3843 (lv "Name" (swank-mop:generic-function-name gf))
3844 (lv "Arguments" (swank-mop:generic-function-lambda-list gf))
3845 (docstring-ispec "Documentation" gf t)
3846 (lv "Method class" (swank-mop:generic-function-method-class gf))
3847 (lv "Method combination"
3848 (swank-mop:generic-function-method-combination gf))
3849 `("Methods: " (:newline))
3850 (loop for method in (funcall *gf-method-getter* gf) append
3851 `((:value ,method ,(inspector-princ
3852 ;; drop the name of the GF
3853 (cdr (method-for-inspect-value method))))
3854 " "
3855 (:action "[remove method]"
3856 ,(let ((m method)) ; LOOP reassigns method
3857 (lambda ()
3858 (remove-method gf m))))
3859 (:newline)))
3860 `((:newline))
3861 (all-slots-for-inspector gf)))))
3862
3863 (defmethod inspect-for-emacs ((method standard-method) inspector)
3864 (declare (ignore inspector))
3865 (values "A method."
3866 `("Method defined on the generic function "
3867 (:value ,(swank-mop:method-generic-function method)
3868 ,(inspector-princ
3869 (swank-mop:generic-function-name
3870 (swank-mop:method-generic-function method))))
3871 (:newline)
3872 ,@(docstring-ispec "Documentation" method t)
3873 "Lambda List: " (:value ,(swank-mop:method-lambda-list method))
3874 (:newline)
3875 "Specializers: " (:value ,(swank-mop:method-specializers method)
3876 ,(inspector-princ (method-specializers-for-inspect method)))
3877 (:newline)
3878 "Qualifiers: " (:value ,(swank-mop:method-qualifiers method))
3879 (:newline)
3880 "Method function: " (:value ,(swank-mop:method-function method))
3881 (:newline)
3882 ,@(all-slots-for-inspector method))))
3883
3884 (defmethod inspect-for-emacs ((class standard-class) inspector)
3885 (declare (ignore inspector))
3886 (values "A class."
3887 `("Name: " (:value ,(class-name class))
3888 (:newline)
3889 "Super classes: "
3890 ,@(common-seperated-spec (swank-mop:class-direct-superclasses class))
3891 (:newline)
3892 "Direct Slots: "
3893 ,@(common-seperated-spec
3894 (swank-mop:class-direct-slots class)
3895 (lambda (slot)
3896 `(:value ,slot ,(inspector-princ (swank-mop:slot-definition-name slot)))))
3897 (:newline)
3898 "Effective Slots: "
3899 ,@(if (swank-mop:class-finalized-p class)
3900 (common-seperated-spec
3901 (swank-mop:class-slots class)
3902 (lambda (slot)
3903 `(:value ,slot ,(inspector-princ
3904 (swank-mop:slot-definition-name slot)))))
3905 '("#<N/A (class not finalized)>"))
3906 (:newline)
3907 ,@(when (documentation class t)
3908 `("Documentation:" (:newline) ,(documentation class t) (:newline)))
3909 "Sub classes: "
3910 ,@(common-seperated-spec (swank-mop:class-direct-subclasses class)
3911 (lambda (sub)
3912 `(:value ,sub ,(inspector-princ (class-name sub)))))
3913 (:newline)
3914 "Precedence List: "
3915 ,@(if (swank-mop:class-finalized-p class)
3916 (common-seperated-spec (swank-mop:class-precedence-list class)
3917 (lambda (class)
3918 `(:value ,class ,(inspector-princ (class-name class)))))
3919 '("#<N/A (class not finalized)>"))
3920 (:newline)
3921 ,@(when (swank-mop:specializer-direct-methods class)
3922 `("It is used as a direct specializer in the following methods:" (:newline)
3923 ,@(loop
3924 for method in (sort (copy-list (swank-mop:specializer-direct-methods class))
3925 #'string< :key (lambda (x)
3926 (symbol-name
3927 (let ((name (swank-mop::generic-function-name
3928 (swank-mop::method-generic-function x))))
3929 (if (symbolp name) name (second name))))))
3930 collect " "
3931 collect `(:value ,method ,(inspector-princ (method-for-inspect-value method)))
3932 collect '(:newline)
3933 if (documentation method t)
3934 collect " Documentation: " and
3935 collect (abbrev-doc (documentation method t)) and
3936 collect '(:newline))))
3937 "Prototype: " ,(if (swank-mop:class-finalized-p class)
3938 `(:value ,(swank-mop:class-prototype class))
3939 '"#<N/A (class not finalized)>")
3940 (:newline)
3941 ,@(all-slots-for-inspector class))))
3942
3943 (defmethod inspect-for-emacs ((slot swank-mop:standard-slot-definition) inspector)
3944 (declare (ignore inspector))
3945 (values "A slot."
3946 `("Name: " (:value ,(swank-mop:slot-definition-name slot))
3947 (:newline)
3948 ,@(when (swank-mop:slot-definition-documentation slot)
3949 `("Documentation:" (:newline)
3950 (:value ,(swank-mop:slot-definition-documentation slot))
3951 (:newline)))
3952 "Init args: " (:value ,(swank-mop:slot-definition-initargs slot)) (:newline)
3953 "Init form: " ,(if (swank-mop:slot-definition-initfunction slot)
3954 `(:value ,(swank-mop:slot-definition-initform slot))
3955 "#<unspecified>") (:newline)
3956 "Init function: " (:value ,(swank-mop:slot-definition-initfunction slot))
3957 (:newline)
3958 ,@(all-slots-for-inspector slot))))
3959
3960 (defmethod inspect-for-emacs ((package package) inspector)
3961 (declare (ignore inspector))
3962 (let ((internal-symbols '())
3963 (external-symbols '()))
3964 (do-symbols (sym package)
3965 (when (eq package (symbol-package sym))
3966 (push sym internal-symbols)
3967 (multiple-value-bind (symbol status)
3968 (find-symbol (symbol-name sym) package)
3969 (declare (ignore symbol))
3970 (when (eql :external status)
3971 (push sym external-symbols)))))
3972 (setf internal-symbols (sort internal-symbols #'string-lessp)
3973 external-symbols (sort external-symbols #'string-lessp))
3974 (values "A package."
3975 `("Name: " (:value ,(package-name package))
3976 (:newline)
3977 "Nick names: " ,@(common-seperated-spec (sort (package-nicknames package) #'string-lessp))
3978 (:newline)
3979 ,@(when (documentation package t)
3980 `("Documentation:" (:newline)
3981 ,(documentation package t) (:newline)))
3982 "Use list: " ,@(common-seperated-spec (sort (package-use-list package) #'string-lessp :key #'package-name)
3983 (lambda (pack)
3984 `(:value ,pack ,(inspector-princ (package-name pack)))))
3985 (:newline)
3986 "Used by list: " ,@(common-seperated-spec (sort (package-used-by-list package) #'string-lessp :key #'package-name)
3987 (lambda (pack)
3988 `(:value ,pack ,(inspector-princ (package-name pack)))))
3989 (:newline)
3990 ,(if (null external-symbols)
3991 "0 external symbols."
3992 `(:value ,external-symbols ,(format nil "~D external symbol~:P." (length external-symbols))))
3993 (:newline)
3994 ,(if (null internal-symbols)
3995 "0 internal symbols."
3996 `(:value ,internal-symbols ,(format nil "~D internal symbol~:P." (length internal-symbols))))
3997 (:newline)
3998 ,(if (null (package-shadowing-symbols package))
3999 "0 shadowed symbols."
4000 `(:value ,(package-shadowing-symbols package)
4001 ,(format nil "~D shadowed symbol~:P." (length (package-shadowing-symbols package)))))))))
4002
4003 (defmethod inspect-for-emacs ((pathname pathname) inspector)
4004 (declare (ignore inspector))
4005 (values (if (wild-pathname-p pathname)
4006 "A wild pathname."
4007 "A pathname.")
4008 (append (label-value-line*
4009 ("Namestring" (namestring pathname))
4010 ("Host" (pathname-host pathname))
4011 ("Device" (pathname-device pathname))
4012 ("Directory" (pathname-directory pathname))
4013 ("Name" (pathname-name pathname))
4014 ("Type" (pathname-type pathname))
4015 ("Version" (pathname-version pathname)))
4016 (unless (or (wild-pathname-p pathname)
4017 (not (probe-file pathname)))
4018 (label-value-line "Truename" (truename pathname))))))
4019
4020 (defmethod inspect-for-emacs ((pathname logical-pathname) inspector)
4021 (declare (ignore inspector))
4022 (values "A logical pathname."
4023 (append
4024 (label-value-line*
4025 ("Namestring" (namestring pathname))
4026 ("Physical pathname: " (translate-logical-pathname pathname)))
4027 `("Host: "
4028 ,(pathname-host pathname)
4029 " (" (:value ,(logical-pathname-translations
4030 (pathname-host pathname)))
4031 "other translations)"
4032 (:newline))
4033 (label-value-line*
4034 ("Directory" (pathname-directory pathname))
4035 ("Name" (pathname-name pathname))
4036 ("Type" (pathname-type pathname))
4037 ("Version" (pathname-version pathname))
4038 ("Truename" (if (not (wild-pathname-p pathname))
4039 (probe-file pathname)))))))
4040
4041 (defmethod inspect-for-emacs ((n number) inspector)
4042 (declare (ignore inspector))
4043 (values "A number." `("Value: " ,(princ-to-string n))))
4044
4045 (defun format-iso8601-time (time-value &optional include-timezone-p)
4046 "Formats a universal time TIME-VALUE in ISO 8601 format, with
4047 the time zone included if INCLUDE-TIMEZONE-P is non-NIL"
4048 ;; Taken from http://www.pvv.ntnu.no/~nsaa/ISO8601.html
4049 ;; Thanks, Nikolai Sandved and Thomas Russ!
4050 (flet ((format-iso8601-timezone (zone)
4051 (if (zerop zone)
4052 "Z"
4053 (multiple-value-bind (h m) (truncate (abs zone) 1.0)
4054 ;; Tricky. Sign of time zone is reversed in ISO 8601
4055 ;; relative to Common Lisp convention!
4056 (format nil "~:[+~;-~]~2,'0D:~2,'0D"
4057 (> zone 0) h (round m))))))
4058 (multiple-value-bind (second minute hour day month year dow dst zone)
4059 (decode-universal-time time-value)
4060 (declare (ignore dow dst))
4061 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0D~:[~*~;~A~]"
4062 year month day hour minute second
4063 include-timezone-p (format-iso8601-timezone zone)))))
4064
4065 (defmethod inspect-for-emacs ((i integer) inspector)
4066 (declare (ignore inspector))
4067 (values "A number."
4068 (append
4069 `(,(format nil "Value: ~D = #x~X = #o~O = #b~,,' ,8:B = ~E"
4070 i i i i i)
4071 (:newline))
4072 (if (< -1 i char-code-limit)
4073 (label-value-line "Corresponding character" (code-char i)))
4074 (label-value-line "Length" (integer-length i))
4075 (ignore-errors
4076 (list "As time: "
4077 (format-iso8601-time i t))))))
4078
4079 (defmethod inspect-for-emacs ((c complex) inspector)
4080 (declare (ignore inspector))
4081 (values "A complex number."
4082 (label-value-line*
4083 ("Real part" (realpart c))
4084 ("Imaginary part" (imagpart c)))))
4085
4086 (defmethod inspect-for-emacs ((r ratio) inspector)
4087 (declare (ignore inspector))
4088 (values "A non-integer ratio."
4089 (label-value-line*
4090 ("Numerator" (numerator r))
4091 ("Denominator" (denominator r))
4092 ("As float" (float r)))))
4093
4094 (defmethod inspect-for-emacs ((f float) inspector)
4095 (declare (ignore inspector))
4096 (multiple-value-bind (significand exponent sign) (decode-float f)
4097 (values "A floating point number."
4098 (append
4099 `("Scientific: " ,(format nil "~E" f) (:newline)
4100 "Decoded: "
4101 (:value ,sign) " * "
4102 (:value ,significand) " * "
4103 (:value ,(float-radix f)) "^" (:value ,exponent) (:newline))
4104 (label-value-line "Digits" (float-digits f))
4105 (label-value-line "Precision" (float-precision f))))))
4106
4107 (defvar *inspectee*)
4108 (defvar *inspectee-parts*)
4109 (defvar *inspectee-actions*)
4110 (defvar *inspector-stack* '())
4111 (defvar *inspector-history* (make-array 10 :adjustable t :fill-pointer 0))
4112 (declaim (type vector *inspector-history*))
4113 (defvar *inspect-length* 30)
4114
4115 (defun reset-inspector ()
4116 (setq *inspectee* nil
4117 *inspector-stack* nil
4118 *inspectee-parts* (make-array 10 :adjustable t :fill-pointer 0)
4119 *inspectee-actions* (make-array 10 :adjustable t :fill-pointer 0)
4120 *inspector-history* (make-array 10 :adjustable t :fill-pointer 0)))
4121
4122 (defslimefun init-inspector (string)
4123 (with-buffer-syntax ()
4124 (reset-inspector)
4125 (inspect-object (eval (read-from-string string)))))
4126
4127 (defun print-part-to-string (value)
4128 (let ((string (to-string value))
4129 (pos (position value *inspector-history*)))
4130 (if pos
4131 (format nil "#~D=~A" pos string)
4132 string)))
4133
4134 (defun inspector-content-for-emacs (specs)
4135 (loop for part in specs collect
4136 (etypecase part
4137 (null ; XXX encourages sloppy programming
4138 nil)
4139 (string part)
4140 (cons (destructure-case part
4141 ((:newline)
4142 (string #\newline))
4143 ((:value obj &optional str)
4144 (value-part-for-emacs obj str))
4145