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

Contents of /slime/swank.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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