Klimi's new dotfiles with stow.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

3795 рядки
139 KiB

5 роки тому
  1. ;;;; swank.lisp --- Server for SLIME commands.
  2. ;;;
  3. ;;; This code has been placed in the Public Domain. All warranties
  4. ;;; are disclaimed.
  5. ;;;
  6. ;;; This file defines the "Swank" TCP server for Emacs to talk to. The
  7. ;;; code in this file is purely portable Common Lisp. We do require a
  8. ;;; smattering of non-portable functions in order to write the server,
  9. ;;; so we have defined them in `swank/backend.lisp' and implemented
  10. ;;; them separately for each Lisp implementation. These extensions are
  11. ;;; available to us here via the `SWANK/BACKEND' package.
  12. (in-package :swank)
  13. ;;;; Top-level variables, constants, macros
  14. (defconstant cl-package (find-package :cl)
  15. "The COMMON-LISP package.")
  16. (defconstant keyword-package (find-package :keyword)
  17. "The KEYWORD package.")
  18. (defconstant default-server-port 4005
  19. "The default TCP port for the server (when started manually).")
  20. (defvar *swank-debug-p* t
  21. "When true, print extra debugging information.")
  22. (defvar *backtrace-pprint-dispatch-table*
  23. (let ((table (copy-pprint-dispatch nil)))
  24. (flet ((print-string (stream string)
  25. (cond (*print-escape*
  26. (escape-string string stream
  27. :map '((#\" . "\\\"")
  28. (#\\ . "\\\\")
  29. (#\newline . "\\n")
  30. (#\return . "\\r"))))
  31. (t (write-string string stream)))))
  32. (set-pprint-dispatch 'string #'print-string 0 table)
  33. table)))
  34. (defvar *backtrace-printer-bindings*
  35. `((*print-pretty* . t)
  36. (*print-readably* . nil)
  37. (*print-level* . 4)
  38. (*print-length* . 6)
  39. (*print-lines* . 1)
  40. (*print-right-margin* . 200)
  41. (*print-pprint-dispatch* . ,*backtrace-pprint-dispatch-table*))
  42. "Pretter settings for printing backtraces.")
  43. (defvar *default-worker-thread-bindings* '()
  44. "An alist to initialize dynamic variables in worker threads.
  45. The list has the form ((VAR . VALUE) ...). Each variable VAR will be
  46. bound to the corresponding VALUE.")
  47. (defun call-with-bindings (alist fun)
  48. "Call FUN with variables bound according to ALIST.
  49. ALIST is a list of the form ((VAR . VAL) ...)."
  50. (if (null alist)
  51. (funcall fun)
  52. (let* ((rlist (reverse alist))
  53. (vars (mapcar #'car rlist))
  54. (vals (mapcar #'cdr rlist)))
  55. (progv vars vals
  56. (funcall fun)))))
  57. (defmacro with-bindings (alist &body body)
  58. "See `call-with-bindings'."
  59. `(call-with-bindings ,alist (lambda () ,@body)))
  60. ;;; The `DEFSLIMEFUN' macro defines a function that Emacs can call via
  61. ;;; RPC.
  62. (defmacro defslimefun (name arglist &body rest)
  63. "A DEFUN for functions that Emacs can call by RPC."
  64. `(progn
  65. (defun ,name ,arglist ,@rest)
  66. ;; see <http://www.franz.com/support/documentation/6.2/\
  67. ;; doc/pages/variables/compiler/\
  68. ;; s_cltl1-compile-file-toplevel-compatibility-p_s.htm>
  69. (eval-when (:compile-toplevel :load-toplevel :execute)
  70. (export ',name (symbol-package ',name)))))
  71. (defun missing-arg ()
  72. "A function that the compiler knows will never to return a value.
  73. You can use (MISSING-ARG) as the initform for defstruct slots that
  74. must always be supplied. This way the :TYPE slot option need not
  75. include some arbitrary initial value like NIL."
  76. (error "A required &KEY or &OPTIONAL argument was not supplied."))
  77. ;;;; Hooks
  78. ;;;
  79. ;;; We use Emacs-like `add-hook' and `run-hook' utilities to support
  80. ;;; simple indirection. The interface is more CLish than the Emacs
  81. ;;; Lisp one.
  82. (defmacro add-hook (place function)
  83. "Add FUNCTION to the list of values on PLACE."
  84. `(pushnew ,function ,place))
  85. (defun run-hook (functions &rest arguments)
  86. "Call each of FUNCTIONS with ARGUMENTS."
  87. (dolist (function functions)
  88. (apply function arguments)))
  89. (defun run-hook-until-success (functions &rest arguments)
  90. "Call each of FUNCTIONS with ARGUMENTS, stop if any function returns
  91. a truthy value"
  92. (loop for hook in functions
  93. thereis (apply hook arguments)))
  94. (defvar *new-connection-hook* '()
  95. "This hook is run each time a connection is established.
  96. The connection structure is given as the argument.
  97. Backend code should treat the connection structure as opaque.")
  98. (defvar *connection-closed-hook* '()
  99. "This hook is run when a connection is closed.
  100. The connection as passed as an argument.
  101. Backend code should treat the connection structure as opaque.")
  102. (defvar *pre-reply-hook* '()
  103. "Hook run (without arguments) immediately before replying to an RPC.")
  104. (defvar *after-init-hook* '()
  105. "Hook run after user init files are loaded.")
  106. ;;;; Connections
  107. ;;;
  108. ;;; Connection structures represent the network connections between
  109. ;;; Emacs and Lisp. Each has a socket stream, a set of user I/O
  110. ;;; streams that redirect to Emacs, and optionally a second socket
  111. ;;; used solely to pipe user-output to Emacs (an optimization). This
  112. ;;; is also the place where we keep everything that needs to be
  113. ;;; freed/closed/killed when we disconnect.
  114. (defstruct (connection
  115. (:constructor %make-connection)
  116. (:conc-name connection.)
  117. (:print-function print-connection))
  118. ;; The listening socket. (usually closed)
  119. (socket (missing-arg) :type t :read-only t)
  120. ;; Character I/O stream of socket connection. Read-only to avoid
  121. ;; race conditions during initialization.
  122. (socket-io (missing-arg) :type stream :read-only t)
  123. ;; Optional dedicated output socket (backending `user-output' slot).
  124. ;; Has a slot so that it can be closed with the connection.
  125. (dedicated-output nil :type (or stream null))
  126. ;; Streams that can be used for user interaction, with requests
  127. ;; redirected to Emacs.
  128. (user-input nil :type (or stream null))
  129. (user-output nil :type (or stream null))
  130. (user-io nil :type (or stream null))
  131. ;; Bindings used for this connection (usually streams)
  132. (env '() :type list)
  133. ;; A stream that we use for *trace-output*; if nil, we user user-output.
  134. (trace-output nil :type (or stream null))
  135. ;; A stream where we send REPL results.
  136. (repl-results nil :type (or stream null))
  137. ;; Cache of macro-indentation information that has been sent to Emacs.
  138. ;; This is used for preparing deltas to update Emacs's knowledge.
  139. ;; Maps: symbol -> indentation-specification
  140. (indentation-cache (make-hash-table :test 'eq) :type hash-table)
  141. ;; The list of packages represented in the cache:
  142. (indentation-cache-packages '())
  143. ;; The communication style used.
  144. (communication-style nil :type (member nil :spawn :sigio :fd-handler))
  145. )
  146. (defun print-connection (conn stream depth)
  147. (declare (ignore depth))
  148. (print-unreadable-object (conn stream :type t :identity t)))
  149. (defstruct (singlethreaded-connection (:include connection)
  150. (:conc-name sconn.))
  151. ;; The SIGINT handler we should restore when the connection is
  152. ;; closed.
  153. saved-sigint-handler
  154. ;; A queue of events. Not all events can be processed in order and
  155. ;; we need a place to stored them.
  156. (event-queue '() :type list)
  157. ;; A counter that is incremented whenever an event is added to the
  158. ;; queue. This is used to detected modifications to the event queue
  159. ;; by interrupts. The counter wraps around.
  160. (events-enqueued 0 :type fixnum))
  161. (defstruct (multithreaded-connection (:include connection)
  162. (:conc-name mconn.))
  163. ;; In multithreaded systems we delegate certain tasks to specific
  164. ;; threads. The `reader-thread' is responsible for reading network
  165. ;; requests from Emacs and sending them to the `control-thread'; the
  166. ;; `control-thread' is responsible for dispatching requests to the
  167. ;; threads that should handle them; the `repl-thread' is the one
  168. ;; that evaluates REPL expressions. The control thread dispatches
  169. ;; all REPL evaluations to the REPL thread and for other requests it
  170. ;; spawns new threads.
  171. reader-thread
  172. control-thread
  173. repl-thread
  174. auto-flush-thread
  175. indentation-cache-thread
  176. ;; List of threads that are currently processing requests. We use
  177. ;; this to find the newest/current thread for an interrupt. In the
  178. ;; future we may store here (thread . request-tag) pairs so that we
  179. ;; can interrupt specific requests.
  180. (active-threads '() :type list)
  181. )
  182. (defvar *emacs-connection* nil
  183. "The connection to Emacs currently in use.")
  184. (defun make-connection (socket stream style)
  185. (let ((conn (funcall (ecase style
  186. (:spawn
  187. #'make-multithreaded-connection)
  188. ((:sigio nil :fd-handler)
  189. #'make-singlethreaded-connection))
  190. :socket socket
  191. :socket-io stream
  192. :communication-style style)))
  193. (run-hook *new-connection-hook* conn)
  194. (send-to-sentinel `(:add-connection ,conn))
  195. conn))
  196. (defslimefun ping (tag)
  197. tag)
  198. (defun safe-backtrace ()
  199. (ignore-errors
  200. (call-with-debugging-environment
  201. (lambda () (backtrace 0 nil)))))
  202. (define-condition swank-error (error)
  203. ((backtrace :initarg :backtrace :reader swank-error.backtrace)
  204. (condition :initarg :condition :reader swank-error.condition))
  205. (:report (lambda (c s) (princ (swank-error.condition c) s)))
  206. (:documentation "Condition which carries a backtrace."))
  207. (defun signal-swank-error (condition &optional (backtrace (safe-backtrace)))
  208. (error 'swank-error :condition condition :backtrace backtrace))
  209. (defvar *debug-on-swank-protocol-error* nil
  210. "When non-nil invoke the system debugger on errors that were
  211. signalled during decoding/encoding the wire protocol. Do not set this
  212. to T unless you want to debug swank internals.")
  213. (defmacro with-swank-error-handler ((connection) &body body)
  214. "Close the connection on internal `swank-error's."
  215. (let ((conn (gensym)))
  216. `(let ((,conn ,connection))
  217. (handler-case
  218. (handler-bind ((swank-error
  219. (lambda (condition)
  220. (when *debug-on-swank-protocol-error*
  221. (invoke-default-debugger condition)))))
  222. (progn . ,body))
  223. (swank-error (condition)
  224. (close-connection ,conn
  225. (swank-error.condition condition)
  226. (swank-error.backtrace condition)))))))
  227. (defmacro with-panic-handler ((connection) &body body)
  228. "Close the connection on unhandled `serious-condition's."
  229. (let ((conn (gensym)))
  230. `(let ((,conn ,connection))
  231. (handler-bind ((serious-condition
  232. (lambda (condition)
  233. (close-connection ,conn condition (safe-backtrace))
  234. (abort condition))))
  235. . ,body))))
  236. (add-hook *new-connection-hook* 'notify-backend-of-connection)
  237. (defun notify-backend-of-connection (connection)
  238. (declare (ignore connection))
  239. (emacs-connected))
  240. ;;;; Utilities
  241. ;;;;; Logging
  242. (defvar *swank-io-package*
  243. (let ((package (make-package :swank-io-package :use '())))
  244. (import '(nil t quote) package)
  245. package))
  246. (defvar *log-events* nil)
  247. (defun init-log-output ()
  248. (unless *log-output*
  249. (setq *log-output* (real-output-stream *error-output*))))
  250. (add-hook *after-init-hook* 'init-log-output)
  251. (defun real-input-stream (stream)
  252. (typecase stream
  253. (synonym-stream
  254. (real-input-stream (symbol-value (synonym-stream-symbol stream))))
  255. (two-way-stream
  256. (real-input-stream (two-way-stream-input-stream stream)))
  257. (t stream)))
  258. (defun real-output-stream (stream)
  259. (typecase stream
  260. (synonym-stream
  261. (real-output-stream (symbol-value (synonym-stream-symbol stream))))
  262. (two-way-stream
  263. (real-output-stream (two-way-stream-output-stream stream)))
  264. (t stream)))
  265. (defvar *event-history* (make-array 40 :initial-element nil)
  266. "A ring buffer to record events for better error messages.")
  267. (defvar *event-history-index* 0)
  268. (defvar *enable-event-history* t)
  269. (defun log-event (format-string &rest args)
  270. "Write a message to *terminal-io* when *log-events* is non-nil.
  271. Useful for low level debugging."
  272. (with-standard-io-syntax
  273. (let ((*print-readably* nil)
  274. (*print-pretty* nil)
  275. (*package* *swank-io-package*))
  276. (when *enable-event-history*
  277. (setf (aref *event-history* *event-history-index*)
  278. (format nil "~?" format-string args))
  279. (setf *event-history-index*
  280. (mod (1+ *event-history-index*) (length *event-history*))))
  281. (when *log-events*
  282. (write-string (escape-non-ascii (format nil "~?" format-string args))
  283. *log-output*)
  284. (force-output *log-output*)))))
  285. (defun event-history-to-list ()
  286. "Return the list of events (older events first)."
  287. (let ((arr *event-history*)
  288. (idx *event-history-index*))
  289. (concatenate 'list (subseq arr idx) (subseq arr 0 idx))))
  290. (defun clear-event-history ()
  291. (fill *event-history* nil)
  292. (setq *event-history-index* 0))
  293. (defun dump-event-history (stream)
  294. (dolist (e (event-history-to-list))
  295. (dump-event e stream)))
  296. (defun dump-event (event stream)
  297. (cond ((stringp event)
  298. (write-string (escape-non-ascii event) stream))
  299. ((null event))
  300. (t
  301. (write-string
  302. (escape-non-ascii (format nil "Unexpected event: ~A~%" event))
  303. stream))))
  304. (defun escape-non-ascii (string)
  305. "Return a string like STRING but with non-ascii chars escaped."
  306. (cond ((ascii-string-p string) string)
  307. (t (with-output-to-string (out)
  308. (loop for c across string do
  309. (cond ((ascii-char-p c) (write-char c out))
  310. (t (format out "\\x~4,'0X" (char-code c)))))))))
  311. (defun ascii-string-p (o)
  312. (and (stringp o)
  313. (every #'ascii-char-p o)))
  314. (defun ascii-char-p (c)
  315. (<= (char-code c) 127))
  316. ;;;;; Helper macros
  317. (defmacro dcase (value &body patterns)
  318. "Dispatch VALUE to one of PATTERNS.
  319. A cross between `case' and `destructuring-bind'.
  320. The pattern syntax is:
  321. ((HEAD . ARGS) . BODY)
  322. The list of patterns is searched for a HEAD `eq' to the car of
  323. VALUE. If one is found, the BODY is executed with ARGS bound to the
  324. corresponding values in the CDR of VALUE."
  325. (let ((operator (gensym "op-"))
  326. (operands (gensym "rand-"))
  327. (tmp (gensym "tmp-")))
  328. `(let* ((,tmp ,value)
  329. (,operator (car ,tmp))
  330. (,operands (cdr ,tmp)))
  331. (case ,operator
  332. ,@(loop for (pattern . body) in patterns collect
  333. (if (eq pattern t)
  334. `(t ,@body)
  335. (destructuring-bind (op &rest rands) pattern
  336. `(,op (destructuring-bind ,rands ,operands
  337. ,@body)))))
  338. ,@(if (eq (caar (last patterns)) t)
  339. '()
  340. `((t (error "dcase failed: ~S" ,tmp))))))))
  341. ;;;; Interrupt handling
  342. ;; Usually we'd like to enter the debugger when an interrupt happens.
  343. ;; But for some operations, in particular send&receive, it's crucial
  344. ;; that those are not interrupted when the mailbox is in an
  345. ;; inconsistent/locked state. Obviously, if send&receive don't work we
  346. ;; can't communicate and the debugger will not work. To solve that
  347. ;; problem, we try to handle interrupts only at certain safe-points.
  348. ;;
  349. ;; Whenever an interrupt happens we call the function
  350. ;; INVOKE-OR-QUEUE-INTERRUPT. Usually this simply invokes the
  351. ;; debugger, but if interrupts are disabled the interrupt is put in a
  352. ;; queue for later processing. At safe-points, we call
  353. ;; CHECK-SLIME-INTERRUPTS which looks at the queue and invokes the
  354. ;; debugger if needed.
  355. ;;
  356. ;; The queue for interrupts is stored in a thread local variable.
  357. ;; WITH-CONNECTION sets it up. WITH-SLIME-INTERRUPTS allows
  358. ;; interrupts, i.e. the debugger is entered immediately. When we call
  359. ;; "user code" or non-problematic code we allow interrupts. When
  360. ;; inside WITHOUT-SLIME-INTERRUPTS, interrupts are queued. When we
  361. ;; switch from "user code" to more delicate operations we need to
  362. ;; disable interrupts. In particular, interrupts should be disabled
  363. ;; for SEND and RECEIVE-IF.
  364. ;; If true execute interrupts, otherwise queue them.
  365. ;; Note: `with-connection' binds *pending-slime-interrupts*.
  366. (defvar *slime-interrupts-enabled*)
  367. (defmacro with-interrupts-enabled% (flag body)
  368. `(progn
  369. ,@(if flag '((check-slime-interrupts)))
  370. (multiple-value-prog1
  371. (let ((*slime-interrupts-enabled* ,flag))
  372. ,@body)
  373. ,@(if flag '((check-slime-interrupts))))))
  374. (defmacro with-slime-interrupts (&body body)
  375. `(with-interrupts-enabled% t ,body))
  376. (defmacro without-slime-interrupts (&body body)
  377. `(with-interrupts-enabled% nil ,body))
  378. (defun queue-thread-interrupt (thread function)
  379. (interrupt-thread thread
  380. (lambda ()
  381. ;; safely interrupt THREAD
  382. (when (invoke-or-queue-interrupt function)
  383. (wake-thread thread)))))
  384. (defun invoke-or-queue-interrupt (function)
  385. (log-event "invoke-or-queue-interrupt: ~a~%" function)
  386. (cond ((not (boundp '*slime-interrupts-enabled*))
  387. (without-slime-interrupts
  388. (funcall function)))
  389. (*slime-interrupts-enabled*
  390. (log-event "interrupts-enabled~%")
  391. (funcall function))
  392. (t
  393. (setq *pending-slime-interrupts*
  394. (nconc *pending-slime-interrupts*
  395. (list function)))
  396. (cond ((cdr *pending-slime-interrupts*)
  397. (log-event "too many queued interrupts~%")
  398. (with-simple-restart (continue "Continue from interrupt")
  399. (handler-bind ((serious-condition #'invoke-slime-debugger))
  400. (check-slime-interrupts))))
  401. (t
  402. (log-event "queue-interrupt: ~a~%" function)
  403. (when *interrupt-queued-handler*
  404. (funcall *interrupt-queued-handler*))
  405. t)))))
  406. ;;; FIXME: poor name?
  407. (defmacro with-io-redirection ((connection) &body body)
  408. "Execute BODY I/O redirection to CONNECTION. "
  409. `(with-bindings (connection.env ,connection)
  410. . ,body))
  411. ;; Thread local variable used for flow-control.
  412. ;; It's bound by `with-connection'.
  413. (defvar *send-counter*)
  414. (defmacro with-connection ((connection) &body body)
  415. "Execute BODY in the context of CONNECTION."
  416. `(let ((connection ,connection)
  417. (function (lambda () . ,body)))
  418. (if (eq *emacs-connection* connection)
  419. (funcall function)
  420. (let ((*emacs-connection* connection)
  421. (*pending-slime-interrupts* '())
  422. (*send-counter* 0))
  423. (without-slime-interrupts
  424. (with-swank-error-handler (connection)
  425. (with-io-redirection (connection)
  426. (call-with-debugger-hook #'swank-debugger-hook
  427. function))))))))
  428. (defun call-with-retry-restart (msg thunk)
  429. (loop (with-simple-restart (retry "~a" msg)
  430. (return (funcall thunk)))))
  431. (defmacro with-retry-restart ((&key (msg "Retry.")) &body body)
  432. (check-type msg string)
  433. `(call-with-retry-restart ,msg (lambda () ,@body)))
  434. (defmacro with-struct* ((conc-name get obj) &body body)
  435. (let ((var (gensym)))
  436. `(let ((,var ,obj))
  437. (macrolet ((,get (slot)
  438. (let ((getter (intern (concatenate 'string
  439. ',(string conc-name)
  440. (string slot))
  441. (symbol-package ',conc-name))))
  442. `(,getter ,',var))))
  443. ,@body))))
  444. (defmacro define-special (name doc)
  445. "Define a special variable NAME with doc string DOC.
  446. This is like defvar, but NAME will not be initialized."
  447. `(progn
  448. (defvar ,name)
  449. (setf (documentation ',name 'variable) ,doc)))
  450. ;;;;; Sentinel
  451. ;;;
  452. ;;; The sentinel thread manages some global lists.
  453. ;;; FIXME: Overdesigned?
  454. (defvar *connections* '()
  455. "List of all active connections, with the most recent at the front.")
  456. (defvar *servers* '()
  457. "A list ((server-socket port thread) ...) describing the listening sockets.
  458. Used to close sockets on server shutdown or restart.")
  459. ;; FIXME: we simply access the global variable here. We could ask the
  460. ;; sentinel thread instead but then we still have the problem that the
  461. ;; connection could be closed before we use it.
  462. (defun default-connection ()
  463. "Return the 'default' Emacs connection.
  464. This connection can be used to talk with Emacs when no specific
  465. connection is in use, i.e. *EMACS-CONNECTION* is NIL.
  466. The default connection is defined (quite arbitrarily) as the most
  467. recently established one."
  468. (car *connections*))
  469. (defun start-sentinel ()
  470. (unless (find-registered 'sentinel)
  471. (let ((thread (spawn #'sentinel :name "Swank Sentinel")))
  472. (register-thread 'sentinel thread))))
  473. (defun sentinel ()
  474. (catch 'exit-sentinel
  475. (loop (sentinel-serve (receive)))))
  476. (defun send-to-sentinel (msg)
  477. (let ((sentinel (find-registered 'sentinel)))
  478. (cond (sentinel (send sentinel msg))
  479. (t (sentinel-serve msg)))))
  480. (defun sentinel-serve (msg)
  481. (dcase msg
  482. ((:add-connection conn)
  483. (push conn *connections*))
  484. ((:close-connection connection condition backtrace)
  485. (close-connection% connection condition backtrace)
  486. (sentinel-maybe-exit))
  487. ((:add-server socket port thread)
  488. (push (list socket port thread) *servers*))
  489. ((:stop-server key port)
  490. (sentinel-stop-server key port)
  491. (sentinel-maybe-exit))))
  492. (defun sentinel-stop-server (key value)
  493. (let ((probe (find value *servers* :key (ecase key
  494. (:socket #'car)
  495. (:port #'cadr)))))
  496. (cond (probe
  497. (setq *servers* (delete probe *servers*))
  498. (destructuring-bind (socket _port thread) probe
  499. (declare (ignore _port))
  500. (ignore-errors (close-socket socket))
  501. (when (and thread
  502. (thread-alive-p thread)
  503. (not (eq thread (current-thread))))
  504. (ignore-errors (kill-thread thread)))))
  505. (t
  506. (warn "No server for ~s: ~s" key value)))))
  507. (defun sentinel-maybe-exit ()
  508. (when (and (null *connections*)
  509. (null *servers*)
  510. (and (current-thread)
  511. (eq (find-registered 'sentinel)
  512. (current-thread))))
  513. (register-thread 'sentinel nil)
  514. (throw 'exit-sentinel nil)))
  515. ;;;;; Misc
  516. (defun use-threads-p ()
  517. (eq (connection.communication-style *emacs-connection*) :spawn))
  518. (defun current-thread-id ()
  519. (thread-id (current-thread)))
  520. (declaim (inline ensure-list))
  521. (defun ensure-list (thing)
  522. (if (listp thing) thing (list thing)))
  523. ;;;;; Symbols
  524. ;; FIXME: this docstring is more confusing than helpful.
  525. (defun symbol-status (symbol &optional (package (symbol-package symbol)))
  526. "Returns one of
  527. :INTERNAL if the symbol is _present_ in PACKAGE as an _internal_ symbol,
  528. :EXTERNAL if the symbol is _present_ in PACKAGE as an _external_ symbol,
  529. :INHERITED if the symbol is _inherited_ by PACKAGE through USE-PACKAGE,
  530. but is not _present_ in PACKAGE,
  531. or NIL if SYMBOL is not _accessible_ in PACKAGE.
  532. Be aware not to get confused with :INTERNAL and how \"internal
  533. symbols\" are defined in the spec; there is a slight mismatch of
  534. definition with the Spec and what's commonly meant when talking
  535. about internal symbols most times. As the spec says:
  536. In a package P, a symbol S is
  537. _accessible_ if S is either _present_ in P itself or was
  538. inherited from another package Q (which implies
  539. that S is _external_ in Q.)
  540. You can check that with: (AND (SYMBOL-STATUS S P) T)
  541. _present_ if either P is the /home package/ of S or S has been
  542. imported into P or exported from P by IMPORT, or
  543. EXPORT respectively.
  544. Or more simply, if S is not _inherited_.
  545. You can check that with: (LET ((STATUS (SYMBOL-STATUS S P)))
  546. (AND STATUS
  547. (NOT (EQ STATUS :INHERITED))))
  548. _external_ if S is going to be inherited into any package that
  549. /uses/ P by means of USE-PACKAGE, MAKE-PACKAGE, or
  550. DEFPACKAGE.
  551. Note that _external_ implies _present_, since to
  552. make a symbol _external_, you'd have to use EXPORT
  553. which will automatically make the symbol _present_.
  554. You can check that with: (EQ (SYMBOL-STATUS S P) :EXTERNAL)
  555. _internal_ if S is _accessible_ but not _external_.
  556. You can check that with: (LET ((STATUS (SYMBOL-STATUS S P)))
  557. (AND STATUS
  558. (NOT (EQ STATUS :EXTERNAL))))
  559. Notice that this is *different* to
  560. (EQ (SYMBOL-STATUS S P) :INTERNAL)
  561. because what the spec considers _internal_ is split up into two
  562. explicit pieces: :INTERNAL, and :INHERITED; just as, for instance,
  563. CL:FIND-SYMBOL does.
  564. The rationale is that most times when you speak about \"internal\"
  565. symbols, you're actually not including the symbols inherited
  566. from other packages, but only about the symbols directly specific
  567. to the package in question.
  568. "
  569. (when package ; may be NIL when symbol is completely uninterned.
  570. (check-type symbol symbol) (check-type package package)
  571. (multiple-value-bind (present-symbol status)
  572. (find-symbol (symbol-name symbol) package)
  573. (and (eq symbol present-symbol) status))))
  574. (defun symbol-external-p (symbol &optional (package (symbol-package symbol)))
  575. "True if SYMBOL is external in PACKAGE.
  576. If PACKAGE is not specified, the home package of SYMBOL is used."
  577. (eq (symbol-status symbol package) :external))
  578. ;;;; TCP Server
  579. (defvar *communication-style* (preferred-communication-style))
  580. (defvar *dont-close* nil
  581. "Default value of :dont-close argument to start-server and
  582. create-server.")
  583. (defparameter *loopback-interface* "localhost")
  584. (defun start-server (port-file &key (style *communication-style*)
  585. (dont-close *dont-close*))
  586. "Start the server and write the listen port number to PORT-FILE.
  587. This is the entry point for Emacs."
  588. (setup-server 0
  589. (lambda (port) (announce-server-port port-file port))
  590. style dont-close nil))
  591. (defun create-server (&key (port default-server-port)
  592. (style *communication-style*)
  593. (dont-close *dont-close*)
  594. interface
  595. backlog)
  596. "Start a SWANK server on PORT running in STYLE.
  597. If DONT-CLOSE is true then the listen socket will accept multiple
  598. connections, otherwise it will be closed after the first.
  599. Optionally, an INTERFACE could be specified and swank will bind
  600. the PORT on this interface. By default, interface is \"localhost\"."
  601. (let ((*loopback-interface* (or interface
  602. *loopback-interface*)))
  603. (setup-server port #'simple-announce-function
  604. style dont-close backlog)))
  605. (defun find-external-format-or-lose (coding-system)
  606. (or (find-external-format coding-system)
  607. (error "Unsupported coding system: ~s" coding-system)))
  608. (defmacro restart-loop (form &body clauses)
  609. "Executes FORM, with restart-case CLAUSES which have a chance to modify FORM's
  610. environment before trying again (by returning normally) or giving up (through an
  611. explicit transfer of control), all within an implicit block named nil.
  612. e.g.: (restart-loop (http-request url) (use-value (new) (setq url new)))"
  613. `(loop (restart-case (return ,form) ,@clauses)))
  614. (defun socket-quest (port backlog)
  615. (restart-loop (create-socket *loopback-interface* port :backlog backlog)
  616. (use-value (&optional (new-port (1+ port)))
  617. :report (lambda (stream) (format stream "Try a port other than ~D" port))
  618. :interactive
  619. (lambda ()
  620. (format *query-io* "Enter port (defaults to ~D): " (1+ port))
  621. (finish-output *query-io*) ; necessary for tunnels
  622. (ignore-errors (list (parse-integer (read-line *query-io*)))))
  623. (setq port new-port))))
  624. (defun setup-server (port announce-fn style dont-close backlog)
  625. (init-log-output)
  626. (let* ((socket (socket-quest port backlog))
  627. (port (local-port socket)))
  628. (funcall announce-fn port)
  629. (labels ((serve () (accept-connections socket style dont-close))
  630. (note () (send-to-sentinel `(:add-server ,socket ,port
  631. ,(current-thread))))
  632. (serve-loop () (note) (loop do (serve) while dont-close)))
  633. (ecase style
  634. (:spawn (initialize-multiprocessing
  635. (lambda ()
  636. (start-sentinel)
  637. (spawn #'serve-loop :name (format nil "Swank ~s" port)))))
  638. ((:fd-handler :sigio)
  639. (note)
  640. (add-fd-handler socket #'serve))
  641. ((nil) (serve-loop))))
  642. port))
  643. (defun stop-server (port)
  644. "Stop server running on PORT."
  645. (send-to-sentinel `(:stop-server :port ,port)))
  646. (defun restart-server (&key (port default-server-port)
  647. (style *communication-style*)
  648. (dont-close *dont-close*))
  649. "Stop the server listening on PORT, then start a new SWANK server
  650. on PORT running in STYLE. If DONT-CLOSE is true then the listen socket
  651. will accept multiple connections, otherwise it will be closed after the
  652. first."
  653. (stop-server port)
  654. (sleep 5)
  655. (create-server :port port :style style :dont-close dont-close))
  656. (defun accept-connections (socket style dont-close)
  657. (unwind-protect
  658. (let ((client (accept-connection socket :external-format nil
  659. :buffering t)))
  660. (authenticate-client client)
  661. (serve-requests (make-connection socket client style)))
  662. (unless dont-close
  663. (send-to-sentinel `(:stop-server :socket ,socket)))))
  664. (defun authenticate-client (stream)
  665. (let ((secret (slime-secret)))
  666. (when secret
  667. (set-stream-timeout stream 20)
  668. (let ((first-val (read-packet stream)))
  669. (unless (and (stringp first-val) (string= first-val secret))
  670. (error "Incoming connection doesn't know the password.")))
  671. (set-stream-timeout stream nil))))
  672. (defun slime-secret ()
  673. "Finds the magic secret from the user's home directory. Returns nil
  674. if the file doesn't exist; otherwise the first line of the file."
  675. (with-open-file (in
  676. (merge-pathnames (user-homedir-pathname) #p".slime-secret")
  677. :if-does-not-exist nil)
  678. (and in (read-line in nil ""))))
  679. (defun serve-requests (connection)
  680. "Read and process all requests on connections."
  681. (etypecase connection
  682. (multithreaded-connection
  683. (spawn-threads-for-connection connection))
  684. (singlethreaded-connection
  685. (ecase (connection.communication-style connection)
  686. ((nil) (simple-serve-requests connection))
  687. (:sigio (install-sigio-handler connection))
  688. (:fd-handler (install-fd-handler connection))))))
  689. (defun stop-serving-requests (connection)
  690. (etypecase connection
  691. (multithreaded-connection
  692. (cleanup-connection-threads connection))
  693. (singlethreaded-connection
  694. (ecase (connection.communication-style connection)
  695. ((nil))
  696. (:sigio (deinstall-sigio-handler connection))
  697. (:fd-handler (deinstall-fd-handler connection))))))
  698. (defun announce-server-port (file port)
  699. (with-open-file (s file
  700. :direction :output
  701. :if-exists :error
  702. :if-does-not-exist :create)
  703. (format s "~S~%" port))
  704. (simple-announce-function port))
  705. (defun simple-announce-function (port)
  706. (when *swank-debug-p*
  707. (format *log-output* "~&;; Swank started at port: ~D.~%" port)
  708. (force-output *log-output*)))
  709. ;;;;; Event Decoding/Encoding
  710. (defun decode-message (stream)
  711. "Read an S-expression from STREAM using the SLIME protocol."
  712. (log-event "decode-message~%")
  713. (without-slime-interrupts
  714. (handler-bind ((error #'signal-swank-error))
  715. (handler-case (read-message stream *swank-io-package*)
  716. (swank-reader-error (c)
  717. `(:reader-error ,(swank-reader-error.packet c)
  718. ,(swank-reader-error.cause c)))))))
  719. (defun encode-message (message stream)
  720. "Write an S-expression to STREAM using the SLIME protocol."
  721. (log-event "encode-message~%")
  722. (without-slime-interrupts
  723. (handler-bind ((error #'signal-swank-error))
  724. (write-message message *swank-io-package* stream))))
  725. ;;;;; Event Processing
  726. (defvar *sldb-quit-restart* nil
  727. "The restart that will be invoked when the user calls sldb-quit.")
  728. ;; Establish a top-level restart and execute BODY.
  729. ;; Execute K if the restart is invoked.
  730. (defmacro with-top-level-restart ((connection k) &body body)
  731. `(with-connection (,connection)
  732. (restart-case
  733. (let ((*sldb-quit-restart* (find-restart 'abort)))
  734. ,@body)
  735. (abort (&optional v)
  736. :report "Return to SLIME's top level."
  737. (declare (ignore v))
  738. (force-user-output)
  739. ,k))))
  740. (defun handle-requests (connection &optional timeout)
  741. "Read and process :emacs-rex requests.
  742. The processing is done in the extent of the toplevel restart."
  743. (with-connection (connection)
  744. (cond (*sldb-quit-restart*
  745. (process-requests timeout))
  746. (t
  747. (tagbody
  748. start
  749. (with-top-level-restart (connection (go start))
  750. (process-requests timeout)))))))
  751. (defun process-requests (timeout)
  752. "Read and process requests from Emacs."
  753. (loop
  754. (multiple-value-bind (event timeout?)
  755. (wait-for-event `(or (:emacs-rex . _)
  756. (:emacs-channel-send . _))
  757. timeout)
  758. (when timeout? (return))
  759. (dcase event
  760. ((:emacs-rex &rest args) (apply #'eval-for-emacs args))
  761. ((:emacs-channel-send channel (selector &rest args))
  762. (channel-send channel selector args))))))
  763. (defun current-socket-io ()
  764. (connection.socket-io *emacs-connection*))
  765. (defun close-connection (connection condition backtrace)
  766. (send-to-sentinel `(:close-connection ,connection ,condition ,backtrace)))
  767. (defun close-connection% (c condition backtrace)
  768. (let ((*debugger-hook* nil))
  769. (log-event "close-connection: ~a ...~%" condition)
  770. (format *log-output* "~&;; swank:close-connection: ~A~%"
  771. (escape-non-ascii (safe-condition-message condition)))
  772. (stop-serving-requests c)
  773. (close (connection.socket-io c))
  774. (when (connection.dedicated-output c)
  775. (close (connection.dedicated-output c)))
  776. (setf *connections* (remove c *connections*))
  777. (run-hook *connection-closed-hook* c)
  778. (when (and condition (not (typep condition 'end-of-file)))
  779. (finish-output *log-output*)
  780. (format *log-output* "~&;; Event history start:~%")
  781. (dump-event-history *log-output*)
  782. (format *log-output* "~
  783. ;; Event history end.~%~
  784. ;; Backtrace:~%~{~A~%~}~
  785. ;; Connection to Emacs lost. [~%~
  786. ;; condition: ~A~%~
  787. ;; type: ~S~%~
  788. ;; style: ~S]~%"
  789. (loop for (i f) in backtrace collect
  790. (ignore-errors
  791. (format nil "~d: ~a" i (escape-non-ascii f))))
  792. (escape-non-ascii (safe-condition-message condition) )
  793. (type-of condition)
  794. (connection.communication-style c)))
  795. (finish-output *log-output*)
  796. (log-event "close-connection ~a ... done.~%" condition)))
  797. ;;;;;; Thread based communication
  798. (defun read-loop (connection)
  799. (let ((input-stream (connection.socket-io connection))
  800. (control-thread (mconn.control-thread connection)))
  801. (with-swank-error-handler (connection)
  802. (loop (send control-thread (decode-message input-stream))))))
  803. (defun dispatch-loop (connection)
  804. (let ((*emacs-connection* connection))
  805. (with-panic-handler (connection)
  806. (loop (dispatch-event connection (receive))))))
  807. (defgeneric thread-for-evaluation (connection id)
  808. (:documentation "Find or create a thread to evaluate the next request.")
  809. (:method ((connection multithreaded-connection) (id (eql t)))
  810. (spawn-worker-thread connection))
  811. (:method ((connection multithreaded-connection) (id (eql :find-existing)))
  812. (car (mconn.active-threads connection)))
  813. (:method (connection (id integer))
  814. (declare (ignorable connection))
  815. (find-thread id))
  816. (:method ((connection singlethreaded-connection) id)
  817. (declare (ignorable connection connection id))
  818. (current-thread)))
  819. (defun interrupt-worker-thread (connection id)
  820. (let ((thread (thread-for-evaluation connection
  821. (cond ((eq id t) :find-existing)
  822. (t id)))))
  823. (log-event "interrupt-worker-thread: ~a ~a~%" id thread)
  824. (if thread
  825. (etypecase connection
  826. (multithreaded-connection
  827. (queue-thread-interrupt thread #'simple-break))
  828. (singlethreaded-connection
  829. (simple-break)))
  830. (encode-message (list :debug-condition (current-thread-id)
  831. (format nil "Thread with id ~a not found"
  832. id))
  833. (current-socket-io)))))
  834. (defun spawn-worker-thread (connection)
  835. (spawn (lambda ()
  836. (with-bindings *default-worker-thread-bindings*
  837. (with-top-level-restart (connection nil)
  838. (apply #'eval-for-emacs
  839. (cdr (wait-for-event `(:emacs-rex . _)))))))
  840. :name "worker"))
  841. (defun add-active-thread (connection thread)
  842. (etypecase connection
  843. (multithreaded-connection
  844. (push thread (mconn.active-threads connection)))
  845. (singlethreaded-connection)))
  846. (defun remove-active-thread (connection thread)
  847. (etypecase connection
  848. (multithreaded-connection
  849. (setf (mconn.active-threads connection)
  850. (delete thread (mconn.active-threads connection) :count 1)))
  851. (singlethreaded-connection)))
  852. (defparameter *event-hook* nil)
  853. (defun dispatch-event (connection event)
  854. "Handle an event triggered either by Emacs or within Lisp."
  855. (log-event "dispatch-event: ~s~%" event)
  856. (or (run-hook-until-success *event-hook* connection event)
  857. (dcase event
  858. ((:emacs-rex form package thread-id id)
  859. (let ((thread (thread-for-evaluation connection thread-id)))
  860. (cond (thread
  861. (add-active-thread connection thread)
  862. (send-event thread `(:emacs-rex ,form ,package ,id)))
  863. (t
  864. (encode-message
  865. (list :invalid-rpc id
  866. (format nil "Thread not found: ~s" thread-id))
  867. (current-socket-io))))))
  868. ((:return thread &rest args)
  869. (remove-active-thread connection thread)
  870. (encode-message `(:return ,@args) (current-socket-io)))
  871. ((:emacs-interrupt thread-id)
  872. (interrupt-worker-thread connection thread-id))
  873. (((:write-string
  874. :debug :debug-condition :debug-activate :debug-return :channel-send
  875. :presentation-start :presentation-end
  876. :new-package :new-features :ed :indentation-update
  877. :eval :eval-no-wait :background-message :inspect :ping
  878. :y-or-n-p :read-from-minibuffer :read-string :read-aborted :test-delay
  879. :write-image :ed-rpc :ed-rpc-no-wait)
  880. &rest _)
  881. (declare (ignore _))
  882. (encode-message event (current-socket-io)))
  883. (((:emacs-pong :emacs-return :emacs-return-string :ed-rpc-forbidden)
  884. thread-id &rest args)
  885. (send-event (find-thread thread-id) (cons (car event) args)))
  886. ((:emacs-channel-send channel-id msg)
  887. (let ((ch (find-channel channel-id)))
  888. (send-event (channel-thread ch) `(:emacs-channel-send ,ch ,msg))))
  889. ((:reader-error packet condition)
  890. (encode-message `(:reader-error ,packet
  891. ,(safe-condition-message condition))
  892. (current-socket-io))))))
  893. (defun send-event (thread event)
  894. (log-event "send-event: ~s ~s~%" thread event)
  895. (let ((c *emacs-connection*))
  896. (etypecase c
  897. (multithreaded-connection
  898. (send thread event))
  899. (singlethreaded-connection
  900. (setf (sconn.event-queue c) (nconc (sconn.event-queue c) (list event)))
  901. (setf (sconn.events-enqueued c) (mod (1+ (sconn.events-enqueued c))
  902. most-positive-fixnum))))))
  903. (defun send-to-emacs (event)
  904. "Send EVENT to Emacs."
  905. ;;(log-event "send-to-emacs: ~a" event)
  906. (without-slime-interrupts
  907. (let ((c *emacs-connection*))
  908. (etypecase c
  909. (multithreaded-connection
  910. (send (mconn.control-thread c) event))
  911. (singlethreaded-connection
  912. (dispatch-event c event)))
  913. (maybe-slow-down))))
  914. ;;;;;; Flow control
  915. ;; After sending N (usually 100) messages we slow down and ping Emacs
  916. ;; to make sure that everything we have sent so far was received.
  917. (defconstant send-counter-limit 100)
  918. (defun maybe-slow-down ()
  919. (let ((counter (incf *send-counter*)))
  920. (when (< send-counter-limit counter)
  921. (setf *send-counter* 0)
  922. (ping-pong))))
  923. (defun ping-pong ()
  924. (let* ((tag (make-tag))
  925. (pattern `(:emacs-pong ,tag)))
  926. (send-to-emacs `(:ping ,(current-thread-id) ,tag))
  927. (wait-for-event pattern)))
  928. (defun wait-for-event (pattern &optional timeout)
  929. "Scan the event queue for PATTERN and return the event.
  930. If TIMEOUT is 'nil wait until a matching event is enqued.
  931. If TIMEOUT is 't only scan the queue without waiting.
  932. The second return value is t if the timeout expired before a matching
  933. event was found."
  934. (log-event "wait-for-event: ~s ~s~%" pattern timeout)
  935. (without-slime-interrupts
  936. (let ((c *emacs-connection*))
  937. (etypecase c
  938. (multithreaded-connection
  939. (receive-if (lambda (e) (event-match-p e pattern)) timeout))
  940. (singlethreaded-connection
  941. (wait-for-event/event-loop c pattern timeout))))))
  942. (defun wait-for-event/event-loop (connection pattern timeout)
  943. (assert (or (not timeout) (eq timeout t)))
  944. (loop
  945. (check-slime-interrupts)
  946. (let ((event (poll-for-event connection pattern)))
  947. (when event (return (car event))))
  948. (let ((events-enqueued (sconn.events-enqueued connection))
  949. (ready (wait-for-input (list (current-socket-io)) timeout)))
  950. (cond ((and timeout (not ready))
  951. (return (values nil t)))
  952. ((or (/= events-enqueued (sconn.events-enqueued connection))
  953. (eq ready :interrupt))
  954. ;; rescan event queue, interrupts may enqueue new events
  955. )
  956. (t
  957. (assert (equal ready (list (current-socket-io))))
  958. (dispatch-event connection
  959. (decode-message (current-socket-io))))))))
  960. (defun poll-for-event (connection pattern)
  961. (let* ((c connection)
  962. (tail (member-if (lambda (e) (event-match-p e pattern))
  963. (sconn.event-queue c))))
  964. (when tail
  965. (setf (sconn.event-queue c)
  966. (nconc (ldiff (sconn.event-queue c) tail) (cdr tail)))
  967. tail)))
  968. ;;; FIXME: Make this use SWANK-MATCH.
  969. (defun event-match-p (event pattern)
  970. (cond ((or (keywordp pattern) (numberp pattern) (stringp pattern)
  971. (member pattern '(nil t)))
  972. (equal event pattern))
  973. ((symbolp pattern) t)
  974. ((consp pattern)
  975. (case (car pattern)
  976. ((or) (some (lambda (p) (event-match-p event p)) (cdr pattern)))
  977. (t (and (consp event)
  978. (and (event-match-p (car event) (car pattern))
  979. (event-match-p (cdr event) (cdr pattern)))))))
  980. (t (error "Invalid pattern: ~S" pattern))))
  981. (defun spawn-threads-for-connection (connection)
  982. (setf (mconn.control-thread connection)
  983. (spawn (lambda () (control-thread connection))
  984. :name "control-thread"))
  985. connection)
  986. (defun control-thread (connection)
  987. (with-struct* (mconn. @ connection)
  988. (setf (@ control-thread) (current-thread))
  989. (setf (@ reader-thread) (spawn (lambda () (read-loop connection))
  990. :name "reader-thread"))
  991. (setf (@ indentation-cache-thread)
  992. (spawn (lambda () (indentation-cache-loop connection))
  993. :name "swank-indentation-cache-thread"))
  994. (dispatch-loop connection)))
  995. (defun cleanup-connection-threads (connection)
  996. (let* ((c connection)
  997. (threads (list (mconn.repl-thread c)
  998. (mconn.reader-thread c)
  999. (mconn.control-thread c)
  1000. (mconn.auto-flush-thread c)
  1001. (mconn.indentation-cache-thread c))))
  1002. (dolist (thread threads)
  1003. (when (and thread
  1004. (thread-alive-p thread)
  1005. (not (equal (current-thread) thread)))
  1006. (ignore-errors (kill-thread thread))))))
  1007. ;;;;;; Signal driven IO
  1008. (defun install-sigio-handler (connection)
  1009. (add-sigio-handler (connection.socket-io connection)
  1010. (lambda () (process-io-interrupt connection)))
  1011. (handle-requests connection t))
  1012. (defvar *io-interupt-level* 0)
  1013. (defun process-io-interrupt (connection)
  1014. (log-event "process-io-interrupt ~d ...~%" *io-interupt-level*)
  1015. (let ((*io-interupt-level* (1+ *io-interupt-level*)))
  1016. (invoke-or-queue-interrupt
  1017. (lambda () (handle-requests connection t))))
  1018. (log-event "process-io-interrupt ~d ... done ~%" *io-interupt-level*))
  1019. (defun deinstall-sigio-handler (connection)
  1020. (log-event "deinstall-sigio-handler...~%")
  1021. (remove-sigio-handlers (connection.socket-io connection))
  1022. (log-event "deinstall-sigio-handler...done~%"))
  1023. ;;;;;; SERVE-EVENT based IO
  1024. (defun install-fd-handler (connection)
  1025. (add-fd-handler (connection.socket-io connection)
  1026. (lambda () (handle-requests connection t)))
  1027. (setf (sconn.saved-sigint-handler connection)
  1028. (install-sigint-handler
  1029. (lambda ()
  1030. (invoke-or-queue-interrupt
  1031. (lambda () (dispatch-interrupt-event connection))))))
  1032. (handle-requests connection t))
  1033. (defun dispatch-interrupt-event (connection)
  1034. (with-connection (connection)
  1035. (dispatch-event connection `(:emacs-interrupt ,(current-thread-id)))))
  1036. (defun deinstall-fd-handler (connection)
  1037. (log-event "deinstall-fd-handler~%")
  1038. (remove-fd-handlers (connection.socket-io connection))
  1039. (install-sigint-handler (sconn.saved-sigint-handler connection)))
  1040. ;;;;;; Simple sequential IO
  1041. (defun simple-serve-requests (connection)
  1042. (unwind-protect
  1043. (with-connection (connection)
  1044. (call-with-user-break-handler
  1045. (lambda ()
  1046. (invoke-or-queue-interrupt
  1047. (lambda () (dispatch-interrupt-event connection))))
  1048. (lambda ()
  1049. (with-simple-restart (close-connection "Close SLIME connection.")
  1050. (let* ((stdin (real-input-stream *standard-input*))
  1051. (*standard-input* (make-repl-input-stream connection
  1052. stdin)))
  1053. (tagbody toplevel
  1054. (with-top-level-restart (connection (go toplevel))
  1055. (simple-repl))))))))
  1056. (close-connection connection nil (safe-backtrace))))
  1057. ;; this is signalled when our custom stream thinks the end-of-file is reached.
  1058. ;; (not when the end-of-file on the socket is reached)
  1059. (define-condition end-of-repl-input (end-of-file) ())
  1060. (defun simple-repl ()
  1061. (loop
  1062. (format t "~a> " (package-string-for-prompt *package*))
  1063. (force-output)
  1064. (let ((form (handler-case (read)
  1065. (end-of-repl-input () (return)))))
  1066. (let ((- form)
  1067. (values (multiple-value-list (eval form))))
  1068. (setq *** ** ** * * (car values)
  1069. /// // // / / values
  1070. +++ ++ ++ + + form)
  1071. (cond ((null values) (format t "; No values~&"))
  1072. (t (mapc (lambda (v) (format t "~s~&" v)) values)))))))
  1073. (defun make-repl-input-stream (connection stdin)
  1074. (make-input-stream
  1075. (lambda () (repl-input-stream-read connection stdin))))
  1076. (defun repl-input-stream-read (connection stdin)
  1077. (loop
  1078. (let* ((socket (connection.socket-io connection))
  1079. (inputs (list socket stdin))
  1080. (ready (wait-for-input inputs)))
  1081. (cond ((eq ready :interrupt)
  1082. (check-slime-interrupts))
  1083. ((member socket ready)
  1084. ;; A Slime request from Emacs is pending; make sure to
  1085. ;; redirect IO to the REPL buffer.
  1086. (with-simple-restart (process-input "Continue reading input.")
  1087. (let ((*sldb-quit-restart* (find-restart 'process-input)))
  1088. (with-io-redirection (connection)
  1089. (handle-requests connection t)))))
  1090. ((member stdin ready)
  1091. ;; User typed something into the *inferior-lisp* buffer,
  1092. ;; so do not redirect.
  1093. (return (read-non-blocking stdin)))
  1094. (t (assert (null ready)))))))
  1095. (defun read-non-blocking (stream)
  1096. (with-output-to-string (str)
  1097. (handler-case
  1098. (loop (let ((c (read-char-no-hang stream)))
  1099. (unless c (return))
  1100. (write-char c str)))
  1101. (end-of-file () (error 'end-of-repl-input :stream stream)))))
  1102. ;;; Channels
  1103. ;; FIXME: should be per connection not global.
  1104. (defvar *channels* '())
  1105. (defvar *channel-counter* 0)
  1106. (defclass channel ()
  1107. ((id :reader channel-id)
  1108. (thread :initarg :thread :initform (current-thread) :reader channel-thread)
  1109. (name :initarg :name :initform nil)))
  1110. (defmethod initialize-instance :after ((ch channel) &key)
  1111. (with-slots (id) ch
  1112. (setf id (incf *channel-counter*))
  1113. (push (cons id ch) *channels*)))
  1114. (defmethod print-object ((c channel) stream)
  1115. (print-unreadable-object (c stream :type t)
  1116. (with-slots (id name) c
  1117. (format stream "~d ~a" id name))))
  1118. (defun find-channel (id)
  1119. (cdr (assoc id *channels*)))
  1120. (defgeneric channel-send (channel selector args))
  1121. (defmacro define-channel-method (selector (channel &rest args) &body body)
  1122. `(defmethod channel-send (,channel (selector (eql ',selector)) args)
  1123. (destructuring-bind ,args args
  1124. . ,body)))
  1125. (defun send-to-remote-channel (channel-id msg)
  1126. (send-to-emacs `(:channel-send ,channel-id ,msg)))
  1127. (defvar *slime-features* nil
  1128. "The feature list that has been sent to Emacs.")
  1129. (defun send-oob-to-emacs (object)
  1130. (send-to-emacs object))
  1131. ;; FIXME: belongs to swank-repl.lisp
  1132. (defun force-user-output ()
  1133. (force-output (connection.user-io *emacs-connection*)))
  1134. (add-hook *pre-reply-hook* 'force-user-output)
  1135. ;; FIXME: belongs to swank-repl.lisp
  1136. (defun clear-user-input ()
  1137. (clear-input (connection.user-input *emacs-connection*)))
  1138. ;; FIXME: not thread save.
  1139. (defvar *tag-counter* 0)
  1140. (defun make-tag ()
  1141. (setq *tag-counter* (mod (1+ *tag-counter*) (expt 2 22))))
  1142. (defun y-or-n-p-in-emacs (format-string &rest arguments)
  1143. "Like y-or-n-p, but ask in the Emacs minibuffer."
  1144. (let ((tag (make-tag))
  1145. (question (apply #'format nil format-string arguments)))
  1146. (force-output)
  1147. (send-to-emacs `(:y-or-n-p ,(current-thread-id) ,tag ,question))
  1148. (third (wait-for-event `(:emacs-return ,tag result)))))
  1149. (defun read-from-minibuffer-in-emacs (prompt &optional initial-value)
  1150. "Ask user a question in Emacs' minibuffer. Returns \"\" when user
  1151. entered nothing, returns NIL when user pressed C-g."
  1152. (check-type prompt string) (check-type initial-value (or null string))
  1153. (let ((tag (make-tag)))
  1154. (force-output)
  1155. (send-to-emacs `(:read-from-minibuffer ,(current-thread-id) ,tag
  1156. ,prompt ,initial-value))
  1157. (third (wait-for-event `(:emacs-return ,tag result)))))
  1158. (defstruct (unreadable-result
  1159. (:constructor make-unreadable-result (string))
  1160. (:copier nil)
  1161. (:print-object
  1162. (lambda (object stream)
  1163. (print-unreadable-object (object stream :type t)
  1164. (princ (unreadable-result-string object) stream)))))
  1165. string)
  1166. (defun symbol-name-for-emacs (symbol)
  1167. (check-type symbol symbol)
  1168. (let ((name (string-downcase (symbol-name symbol))))
  1169. (if (keywordp symbol)
  1170. (concatenate 'string ":" name)
  1171. name)))
  1172. (defun process-form-for-emacs (form)
  1173. "Returns a string which emacs will read as equivalent to
  1174. FORM. FORM can contain lists, strings, characters, symbols and
  1175. numbers.
  1176. Characters are converted emacs' ?<char> notaion, strings are left
  1177. as they are (except for espacing any nested \" chars, numbers are
  1178. printed in base 10 and symbols are printed as their symbol-name
  1179. converted to lower case."
  1180. (etypecase form
  1181. (string (format nil "~S" form))
  1182. (cons (format nil "(~A . ~A)"
  1183. (process-form-for-emacs (car form))
  1184. (process-form-for-emacs (cdr form))))
  1185. (character (format nil "?~C" form))
  1186. (symbol (symbol-name-for-emacs form))
  1187. (number (let ((*print-base* 10))
  1188. (princ-to-string form)))))
  1189. (defun wait-for-emacs-return (tag)
  1190. (let ((event (caddr (wait-for-event `(:emacs-return ,tag result)))))
  1191. (dcase event
  1192. ((:unreadable value) (make-unreadable-result value))
  1193. ((:ok value) value)
  1194. ((:error kind . data) (error "~a: ~{~a~}" kind data))
  1195. ((:abort) (abort))
  1196. ;; only in reply to :ed-rpc{-no-wait} events.
  1197. ((:ed-rpc-forbidden fn) (error "ED-RPC forbidden for ~a" fn)))))
  1198. (defun eval-in-emacs (form &optional nowait)
  1199. "Eval FORM in Emacs.
  1200. `slime-enable-evaluate-in-emacs' should be set to T on the Emacs side."
  1201. (cond (nowait
  1202. (send-to-emacs `(:eval-no-wait ,(process-form-for-emacs form))))
  1203. (t
  1204. (force-output)
  1205. (let ((tag (make-tag)))
  1206. (send-to-emacs `(:eval ,(current-thread-id) ,tag
  1207. ,(process-form-for-emacs form)))
  1208. (wait-for-emacs-return tag)))))
  1209. (defun ed-rpc-no-wait (fn &rest args)
  1210. "Invoke FN in Emacs (or some lesser editor) and don't wait for the result."
  1211. (send-to-emacs `(:ed-rpc-no-wait ,(symbol-name-for-emacs fn) ,@args))
  1212. (values))
  1213. (defun ed-rpc (fn &rest args)
  1214. "Invoke FN in Emacs (or some lesser editor). FN should be defined in
  1215. Emacs Lisp via `defslimefun' or otherwise marked as RPCallable."
  1216. (let ((tag (make-tag)))
  1217. (send-to-emacs `(:ed-rpc ,(current-thread-id) ,tag
  1218. ,(symbol-name-for-emacs fn)
  1219. ,@args))
  1220. (wait-for-emacs-return tag)))
  1221. (defvar *swank-wire-protocol-version* nil
  1222. "The version of the swank/slime communication protocol.")
  1223. (defslimefun connection-info ()
  1224. "Return a key-value list of the form:
  1225. \(&key PID STYLE LISP-IMPLEMENTATION MACHINE FEATURES PACKAGE VERSION)
  1226. PID: is the process-id of Lisp process (or nil, depending on the STYLE)
  1227. STYLE: the communication style
  1228. LISP-IMPLEMENTATION: a list (&key TYPE NAME VERSION)
  1229. FEATURES: a list of keywords
  1230. PACKAGE: a list (&key NAME PROMPT)
  1231. VERSION: the protocol version"
  1232. (let ((c *emacs-connection*))
  1233. (setq *slime-features* *features*)
  1234. `(:pid ,(getpid) :style ,(connection.communication-style c)
  1235. :encoding (:coding-systems
  1236. ,(loop for cs in '("utf-8-unix" "iso-latin-1-unix")
  1237. when (find-external-format cs) collect cs))
  1238. :lisp-implementation (:type ,(lisp-implementation-type)
  1239. :name ,(lisp-implementation-type-name)
  1240. :version ,(lisp-implementation-version)
  1241. :program ,(lisp-implementation-program))
  1242. :machine (:instance ,(machine-instance)
  1243. :type ,(machine-type)
  1244. :version ,(machine-version))
  1245. :features ,(features-for-emacs)
  1246. :modules ,*modules*
  1247. :package (:name ,(package-name *package*)
  1248. :prompt ,(package-string-for-prompt *package*))
  1249. :version ,*swank-wire-protocol-version*)))
  1250. (defun debug-on-swank-error ()
  1251. (assert (eq *debug-on-swank-protocol-error* *debug-swank-backend*))
  1252. *debug-on-swank-protocol-error*)
  1253. (defun (setf debug-on-swank-error) (new-value)
  1254. (setf *debug-on-swank-protocol-error* new-value)
  1255. (setf *debug-swank-backend* new-value))
  1256. (defslimefun toggle-debug-on-swank-error ()
  1257. (setf (debug-on-swank-error) (not (debug-on-swank-error))))
  1258. ;;;; Reading and printing
  1259. (define-special *buffer-package*
  1260. "Package corresponding to slime-buffer-package.
  1261. EVAL-FOR-EMACS binds *buffer-package*. Strings originating from a slime
  1262. buffer are best read in this package. See also FROM-STRING and TO-STRING.")
  1263. (define-special *buffer-readtable*
  1264. "Readtable associated with the current buffer")
  1265. (defmacro with-buffer-syntax ((&optional package) &body body)
  1266. "Execute BODY with appropriate *package* and *readtable* bindings.
  1267. This should be used for code that is conceptionally executed in an
  1268. Emacs buffer."
  1269. `(call-with-buffer-syntax ,package (lambda () ,@body)))
  1270. (defun call-with-buffer-syntax (package fun)
  1271. (let ((*package* (if package
  1272. (guess-buffer-package package)
  1273. *buffer-package*)))
  1274. ;; Don't shadow *readtable* unnecessarily because that prevents
  1275. ;; the user from assigning to it.
  1276. (if (eq *readtable* *buffer-readtable*)
  1277. (call-with-syntax-hooks fun)
  1278. (let ((*readtable* *buffer-readtable*))
  1279. (call-with-syntax-hooks fun)))))
  1280. (defmacro without-printing-errors ((&key object stream
  1281. (msg "<<error printing object>>"))
  1282. &body body)
  1283. "Catches errors during evaluation of BODY and prints MSG instead."
  1284. `(handler-case (progn ,@body)
  1285. (serious-condition ()
  1286. ,(cond ((and stream object)
  1287. (let ((gstream (gensym "STREAM+")))
  1288. `(let ((,gstream ,stream))
  1289. (print-unreadable-object (,object ,gstream :type t
  1290. :identity t)
  1291. (write-string ,msg ,gstream)))))
  1292. (stream
  1293. `(write-string ,msg ,stream))
  1294. (object
  1295. `(with-output-to-string (s)
  1296. (print-unreadable-object (,object s :type t :identity t)
  1297. (write-string ,msg s))))
  1298. (t msg)))))
  1299. (defun to-string (object)
  1300. "Write OBJECT in the *BUFFER-PACKAGE*.
  1301. The result may not be readable. Handles problems with PRINT-OBJECT methods
  1302. gracefully."
  1303. (with-buffer-syntax ()
  1304. (let ((*print-readably* nil))
  1305. (without-printing-errors (:object object :stream nil)
  1306. (prin1-to-string object)))))
  1307. (defun from-string (string)
  1308. "Read string in the *BUFFER-PACKAGE*"
  1309. (with-buffer-syntax ()
  1310. (let ((*read-suppress* nil))
  1311. (values (read-from-string string)))))
  1312. (defun parse-string (string package)
  1313. "Read STRING in PACKAGE."
  1314. (with-buffer-syntax (package)
  1315. (let ((*read-suppress* nil))
  1316. (read-from-string string))))
  1317. ;; FIXME: deal with #\| etc. hard to do portably.
  1318. (defun tokenize-symbol (string)
  1319. "STRING is interpreted as the string representation of a symbol
  1320. and is tokenized accordingly. The result is returned in three
  1321. values: The package identifier part, the actual symbol identifier
  1322. part, and a flag if the STRING represents a symbol that is
  1323. internal to the package identifier part. (Notice that the flag is
  1324. also true with an empty package identifier part, as the STRING is
  1325. considered to represent a symbol internal to some current package.)"
  1326. (let ((package (let ((pos (position #\: string)))
  1327. (if pos (subseq string 0 pos) nil)))
  1328. (symbol (let ((pos (position #\: string :from-end t)))
  1329. (if pos (subseq string (1+ pos)) string)))
  1330. (internp (not (= (count #\: string) 1))))
  1331. (values symbol package internp)))
  1332. (defun tokenize-symbol-thoroughly (string)
  1333. "This version of TOKENIZE-SYMBOL handles escape characters."
  1334. (let ((package nil)
  1335. (token (make-array (length string) :element-type 'character
  1336. :fill-pointer 0))
  1337. (backslash nil)
  1338. (vertical nil)
  1339. (internp nil))
  1340. (loop for char across string do
  1341. (cond
  1342. (backslash
  1343. (vector-push-extend char token)
  1344. (setq backslash nil))
  1345. ((char= char #\\) ; Quotes next character, even within |...|
  1346. (setq backslash t))
  1347. ((char= char #\|)
  1348. (setq vertical (not vertical)))
  1349. (vertical
  1350. (vector-push-extend char token))
  1351. ((char= char #\:)
  1352. (cond ((and package internp)
  1353. (return-from tokenize-symbol-thoroughly))
  1354. (package
  1355. (setq internp t))
  1356. (t
  1357. (setq package token
  1358. token (make-array (length string)
  1359. :element-type 'character
  1360. :fill-pointer 0)))))
  1361. (t
  1362. (vector-push-extend (casify-char char) token))))
  1363. (unless vertical
  1364. (values token package (or (not package) internp)))))
  1365. (defun untokenize-symbol (package-name internal-p symbol-name)
  1366. "The inverse of TOKENIZE-SYMBOL.
  1367. (untokenize-symbol \"quux\" nil \"foo\") ==> \"quux:foo\"
  1368. (untokenize-symbol \"quux\" t \"foo\") ==> \"quux::foo\"
  1369. (untokenize-symbol nil nil \"foo\") ==> \"foo\"
  1370. "
  1371. (cond ((not package-name) symbol-name)
  1372. (internal-p (cat package-name "::" symbol-name))
  1373. (t (cat package-name ":" symbol-name))))
  1374. (defun casify-char (char)
  1375. "Convert CHAR accoring to readtable-case."
  1376. (ecase (readtable-case *readtable*)
  1377. (:preserve char)
  1378. (:upcase (char-upcase char))
  1379. (:downcase (char-downcase char))
  1380. (:invert (if (upper-case-p char)
  1381. (char-downcase char)
  1382. (char-upcase char)))))
  1383. (defun find-symbol-with-status (symbol-name status
  1384. &optional (package *package*))
  1385. (multiple-value-bind (symbol flag) (find-symbol symbol-name package)
  1386. (if (and flag (eq flag status))
  1387. (values symbol flag)
  1388. (values nil nil))))
  1389. (defun parse-symbol (string &optional (package *package*))
  1390. "Find the symbol named STRING.
  1391. Return the symbol and a flag indicating whether the symbols was found."
  1392. (multiple-value-bind (sname pname internalp)
  1393. (tokenize-symbol-thoroughly string)
  1394. (when sname
  1395. (let ((package (cond ((string= pname "") keyword-package)
  1396. (pname (find-package pname))
  1397. (t package))))
  1398. (if package
  1399. (multiple-value-bind (symbol flag)
  1400. (if internalp
  1401. (find-symbol sname package)
  1402. (find-symbol-with-status sname ':external package))
  1403. (values symbol flag sname package))
  1404. (values nil nil nil nil))))))
  1405. (defun parse-symbol-or-lose (string &optional (package *package*))
  1406. (multiple-value-bind (symbol status) (parse-symbol string package)
  1407. (if status
  1408. (values symbol status)
  1409. (error "Unknown symbol: ~A [in ~A]" string package))))
  1410. (defun parse-package (string)
  1411. "Find the package named STRING.
  1412. Return the package or nil."
  1413. ;; STRING comes usually from a (in-package STRING) form.
  1414. (ignore-errors
  1415. (find-package (let ((*package* *swank-io-package*))
  1416. (read-from-string string)))))
  1417. (defun unparse-name (string)
  1418. "Print the name STRING according to the current printer settings."
  1419. ;; this is intended for package or symbol names
  1420. (subseq (prin1-to-string (make-symbol string)) 2))
  1421. (defun guess-package (string)
  1422. "Guess which package corresponds to STRING.
  1423. Return nil if no package matches."
  1424. (when string
  1425. (or (find-package string)
  1426. (parse-package string)
  1427. (if (find #\! string) ; for SBCL
  1428. (guess-package (substitute #\- #\! string))))))
  1429. (defvar *readtable-alist* (default-readtable-alist)
  1430. "An alist mapping package names to readtables.")
  1431. (defun guess-buffer-readtable (package-name)
  1432. (let ((package (guess-package package-name)))
  1433. (or (and package
  1434. (cdr (assoc (package-name package) *readtable-alist*
  1435. :test #'string=)))
  1436. *readtable*)))
  1437. ;;;; Evaluation
  1438. (defvar *pending-continuations* '()
  1439. "List of continuations for Emacs. (thread local)")
  1440. (defun guess-buffer-package (string)
  1441. "Return a package for STRING.
  1442. Fall back to the current if no such package exists."
  1443. (or (and string (guess-package string))
  1444. *package*))
  1445. (defun eval-for-emacs (form buffer-package id)
  1446. "Bind *BUFFER-PACKAGE* to BUFFER-PACKAGE and evaluate FORM.
  1447. Return the result to the continuation ID.
  1448. Errors are trapped and invoke our debugger."
  1449. (let (ok result condition)
  1450. (unwind-protect
  1451. (let ((*buffer-package* (guess-buffer-package buffer-package))
  1452. (*buffer-readtable* (guess-buffer-readtable buffer-package))
  1453. (*pending-continuations* (cons id *pending-continuations*)))
  1454. (check-type *buffer-package* package)
  1455. (check-type *buffer-readtable* readtable)
  1456. ;; APPLY would be cleaner than EVAL.
  1457. ;; (setq result (apply (car form) (cdr form)))
  1458. (handler-bind ((t (lambda (c) (setf condition c))))
  1459. (setq result (with-slime-interrupts (eval form))))
  1460. (run-hook *pre-reply-hook*)
  1461. (setq ok t))
  1462. (send-to-emacs `(:return ,(current-thread)
  1463. ,(if ok
  1464. `(:ok ,result)
  1465. `(:abort ,(prin1-to-string condition)))
  1466. ,id)))))
  1467. (defvar *echo-area-prefix* "=> "
  1468. "A prefix that `format-values-for-echo-area' should use.")
  1469. (defun format-values-for-echo-area (values)
  1470. (with-buffer-syntax ()
  1471. (let ((*print-readably* nil))
  1472. (cond ((null values) "; No value")
  1473. ((and (integerp (car values)) (null (cdr values)))
  1474. (let ((i (car values)))
  1475. (format nil "~A~D (~a bit~:p, #x~X, #o~O, #b~B)"
  1476. *echo-area-prefix*
  1477. i (integer-length i) i i i)))
  1478. ((and (typep (car values) 'ratio)
  1479. (null (cdr values))
  1480. (ignore-errors
  1481. ;; The ratio may be to large to be represented as a single float
  1482. (format nil "~A~D (~:*~f)"
  1483. *echo-area-prefix*
  1484. (car values)))))
  1485. (t (format nil "~a~{~S~^, ~}" *echo-area-prefix* values))))))
  1486. (defmacro values-to-string (values)
  1487. `(format-values-for-echo-area (multiple-value-list ,values)))
  1488. (defslimefun interactive-eval (string)
  1489. (with-buffer-syntax ()
  1490. (with-retry-restart (:msg "Retry SLIME interactive evaluation request.")
  1491. (let ((values (multiple-value-list (eval (from-string string)))))
  1492. (finish-output)
  1493. (format-values-for-echo-area values)))))
  1494. (defslimefun eval-and-grab-output (string)
  1495. (with-buffer-syntax ()
  1496. (with-retry-restart (:msg "Retry SLIME evaluation request.")
  1497. (let* ((s (make-string-output-stream))
  1498. (*standard-output* s)
  1499. (values (multiple-value-list (eval (from-string string)))))
  1500. (list (get-output-stream-string s)
  1501. (format nil "~{~S~^~%~}" values))))))
  1502. (defun eval-region (string)
  1503. "Evaluate STRING.
  1504. Return the results of the last form as a list and as secondary value the
  1505. last form."
  1506. (with-input-from-string (stream string)
  1507. (let (- values)
  1508. (loop
  1509. (let ((form (read stream nil stream)))
  1510. (when (eq form stream)
  1511. (finish-output)
  1512. (return (values values -)))
  1513. (setq - form)
  1514. (setq values (multiple-value-list (eval form)))
  1515. (finish-output))))))
  1516. (defslimefun interactive-eval-region (string)
  1517. (with-buffer-syntax ()
  1518. (with-retry-restart (:msg "Retry SLIME interactive evaluation request.")
  1519. (format-values-for-echo-area (eval-region string)))))
  1520. (defslimefun re-evaluate-defvar (form)
  1521. (with-buffer-syntax ()
  1522. (with-retry-restart (:msg "Retry SLIME evaluation request.")
  1523. (let ((form (read-from-string form)))
  1524. (destructuring-bind (dv name &optional value doc) form
  1525. (declare (ignore value doc))
  1526. (assert (eq dv 'defvar))
  1527. (makunbound name)
  1528. (prin1-to-string (eval form)))))))
  1529. (defvar *swank-pprint-bindings*
  1530. `((*print-pretty* . t)
  1531. (*print-level* . nil)
  1532. (*print-length* . nil)
  1533. (*print-circle* . t)
  1534. (*print-gensym* . t)
  1535. (*print-readably* . nil))
  1536. "A list of variables bindings during pretty printing.
  1537. Used by pprint-eval.")
  1538. (defun swank-pprint (values)
  1539. "Bind some printer variables and pretty print each object in VALUES."
  1540. (with-buffer-syntax ()
  1541. (with-bindings *swank-pprint-bindings*
  1542. (cond ((null values) "; No value")
  1543. (t (with-output-to-string (*standard-output*)
  1544. (dolist (o values)
  1545. (pprint o)
  1546. (terpri))))))))
  1547. (defslimefun pprint-eval (string)
  1548. (with-buffer-syntax ()
  1549. (let* ((s (make-string-output-stream))
  1550. (values
  1551. (let ((*standard-output* s)
  1552. (*trace-output* s))
  1553. (multiple-value-list (eval (read-from-string string))))))
  1554. (cat (get-output-stream-string s)
  1555. (swank-pprint values)))))
  1556. (defslimefun set-package (name)
  1557. "Set *package* to the package named NAME.
  1558. Return the full package-name and the string to use in the prompt."
  1559. (let ((p (guess-package name)))
  1560. (assert (packagep p) nil "Package ~a doesn't exist." name)
  1561. (setq *package* p)
  1562. (list (package-name p) (package-string-for-prompt p))))
  1563. (defun cat (&rest strings)
  1564. "Concatenate all arguments and make the result a string."
  1565. (with-output-to-string (out)
  1566. (dolist (s strings)
  1567. (etypecase s
  1568. (string (write-string s out))
  1569. (character (write-char s out))))))
  1570. (defun truncate-string (string width &optional ellipsis)
  1571. (let ((len (length string)))
  1572. (cond ((< len width) string)
  1573. (ellipsis (cat (subseq string 0 width) ellipsis))
  1574. (t (subseq string 0 width)))))
  1575. (defun call/truncated-output-to-string (length function
  1576. &optional (ellipsis ".."))
  1577. "Call FUNCTION with a new stream, return the output written to the stream.
  1578. If FUNCTION tries to write more than LENGTH characters, it will be
  1579. aborted and return immediately with the output written so far."
  1580. (let ((buffer (make-string (+ length (length ellipsis))))
  1581. (fill-pointer 0))
  1582. (block buffer-full
  1583. (flet ((write-output (string)
  1584. (let* ((free (- length fill-pointer))
  1585. (count (min free (length string))))
  1586. (replace buffer string :start1 fill-pointer :end2 count)
  1587. (incf fill-pointer count)
  1588. (when (> (length string) free)
  1589. (replace buffer ellipsis :start1 fill-pointer)
  1590. (return-from buffer-full buffer)))))
  1591. (let ((stream (make-output-stream #'write-output)))
  1592. (funcall function stream)
  1593. (finish-output stream)
  1594. (subseq buffer 0 fill-pointer))))))
  1595. (defmacro with-string-stream ((var &key length bindings)
  1596. &body body)
  1597. (cond ((and (not bindings) (not length))
  1598. `(with-output-to-string (,var) . ,body))
  1599. ((not bindings)
  1600. `(call/truncated-output-to-string
  1601. ,length (lambda (,var) . ,body)))
  1602. (t
  1603. `(with-bindings ,bindings
  1604. (with-string-stream (,var :length ,length)
  1605. . ,body)))))
  1606. (defun to-line (object &optional width)
  1607. "Print OBJECT to a single line. Return the string."
  1608. (let ((width (or width 512)))
  1609. (without-printing-errors (:object object :stream nil)
  1610. (with-string-stream (stream :length width)
  1611. (write object :stream stream :right-margin width :lines 1)))))
  1612. (defun escape-string (string stream &key length (map '((#\" . "\\\"")
  1613. (#\\ . "\\\\"))))
  1614. "Write STRING to STREAM surronded by double-quotes.
  1615. LENGTH -- if non-nil truncate output after LENGTH chars.
  1616. MAP -- rewrite the chars in STRING according to this alist."
  1617. (let ((limit (or length array-dimension-limit)))
  1618. (write-char #\" stream)
  1619. (loop for c across string
  1620. for i from 0 do
  1621. (when (= i limit)
  1622. (write-string "..." stream)
  1623. (return))
  1624. (let ((probe (assoc c map)))
  1625. (cond (probe (write-string (cdr probe) stream))
  1626. (t (write-char c stream)))))
  1627. (write-char #\" stream)))
  1628. ;;;; Prompt
  1629. ;; FIXME: do we really need 45 lines of code just to figure out the
  1630. ;; prompt?
  1631. (defvar *canonical-package-nicknames*
  1632. `((:common-lisp-user . :cl-user))
  1633. "Canonical package names to use instead of shortest name/nickname.")
  1634. (defvar *auto-abbreviate-dotted-packages* t
  1635. "Abbreviate dotted package names to their last component if T.")
  1636. (defun package-string-for-prompt (package)
  1637. "Return the shortest nickname (or canonical name) of PACKAGE."
  1638. (unparse-name
  1639. (or (canonical-package-nickname package)
  1640. (auto-abbreviated-package-name package)
  1641. (shortest-package-nickname package))))
  1642. (defun canonical-package-nickname (package)
  1643. "Return the canonical package nickname, if any, of PACKAGE."
  1644. (let ((name (cdr (assoc (package-name package) *canonical-package-nicknames*
  1645. :test #'string=))))
  1646. (and name (string name))))
  1647. (defun auto-abbreviated-package-name (package)
  1648. "Return an abbreviated 'name' for PACKAGE.
  1649. N.B. this is not an actual package name or nickname."
  1650. (when *auto-abbreviate-dotted-packages*
  1651. (loop with package-name = (package-name package)
  1652. with offset = nil
  1653. do (let ((last-dot-pos (position #\. package-name :end offset
  1654. :from-end t)))
  1655. (unless last-dot-pos
  1656. (return nil))
  1657. ;; If a dot chunk contains only numbers, that chunk most
  1658. ;; likely represents a version number; so we collect the
  1659. ;; next chunks, too, until we find one with meat.
  1660. (let ((name (subseq package-name (1+ last-dot-pos) offset)))
  1661. (if (notevery #'digit-char-p name)
  1662. (return (subseq package-name (1+ last-dot-pos)))
  1663. (setq offset last-dot-pos)))))))
  1664. (defun shortest-package-nickname (package)
  1665. "Return the shortest nickname of PACKAGE."
  1666. (loop for name in (cons (package-name package) (package-nicknames package))
  1667. for shortest = name then (if (< (length name) (length shortest))
  1668. name
  1669. shortest)
  1670. finally (return shortest)))
  1671. (defslimefun ed-in-emacs (&optional what)
  1672. "Edit WHAT in Emacs.
  1673. WHAT can be:
  1674. A pathname or a string,
  1675. A list (PATHNAME-OR-STRING &key LINE COLUMN POSITION),
  1676. A function name (symbol or cons),
  1677. NIL. "
  1678. (flet ((canonicalize-filename (filename)
  1679. (pathname-to-filename (or (probe-file filename) filename))))
  1680. (let ((target
  1681. (etypecase what
  1682. (null nil)
  1683. ((or string pathname)
  1684. `(:filename ,(canonicalize-filename what)))
  1685. ((cons (or string pathname) *)
  1686. `(:filename ,(canonicalize-filename (car what)) ,@(cdr what)))
  1687. ((or symbol cons)
  1688. `(:function-name ,(prin1-to-string what))))))
  1689. (cond (*emacs-connection* (send-oob-to-emacs `(:ed ,target)))
  1690. ((default-connection)
  1691. (with-connection ((default-connection))
  1692. (send-oob-to-emacs `(:ed ,target))))
  1693. (t (error "No connection"))))))
  1694. (defslimefun inspect-in-emacs (what &key wait)
  1695. "Inspect WHAT in Emacs. If WAIT is true (default NIL) blocks until the
  1696. inspector has been closed in Emacs."
  1697. (flet ((send-it ()
  1698. (let ((tag (when wait (make-tag)))
  1699. (thread (when wait (current-thread-id))))
  1700. (with-buffer-syntax ()
  1701. (reset-inspector)
  1702. (send-oob-to-emacs `(:inspect ,(inspect-object what)
  1703. ,thread
  1704. ,tag)))
  1705. (when wait
  1706. (wait-for-event `(:emacs-return ,tag result))))))
  1707. (cond
  1708. (*emacs-connection*
  1709. (send-it))
  1710. ((default-connection)
  1711. (with-connection ((default-connection))
  1712. (send-it))))
  1713. what))
  1714. (defslimefun value-for-editing (form)
  1715. "Return a readable value of FORM for editing in Emacs.
  1716. FORM is expected, but not required, to be SETF'able."
  1717. ;; FIXME: Can we check FORM for setfability? -luke (12/Mar/2005)
  1718. (with-buffer-syntax ()
  1719. (let* ((value (eval (read-from-string form)))
  1720. (*print-length* nil))
  1721. (prin1-to-string value))))
  1722. (defslimefun commit-edited-value (form value)
  1723. "Set the value of a setf'able FORM to VALUE.
  1724. FORM and VALUE are both strings from Emacs."
  1725. (with-buffer-syntax ()
  1726. (eval `(setf ,(read-from-string form)
  1727. ,(read-from-string (concatenate 'string "`" value))))
  1728. t))
  1729. (defun background-message (format-string &rest args)
  1730. "Display a message in Emacs' echo area.
  1731. Use this function for informative messages only. The message may even
  1732. be dropped if we are too busy with other things."
  1733. (when *emacs-connection*
  1734. (send-to-emacs `(:background-message
  1735. ,(apply #'format nil format-string args)))))
  1736. ;; This is only used by the test suite.
  1737. (defun sleep-for (seconds)
  1738. "Sleep for at least SECONDS seconds.
  1739. This is just like cl:sleep but guarantees to sleep
  1740. at least SECONDS."
  1741. (let* ((start (get-internal-real-time))
  1742. (end (+ start
  1743. (* seconds internal-time-units-per-second))))
  1744. (loop
  1745. (let ((now (get-internal-real-time)))
  1746. (cond ((< end now) (return))
  1747. (t (sleep (/ (- end now)
  1748. internal-time-units-per-second))))))))
  1749. ;;;; Debugger
  1750. (defun invoke-slime-debugger (condition)
  1751. "Sends a message to Emacs declaring that the debugger has been entered,
  1752. then waits to handle further requests from Emacs. Eventually returns
  1753. after Emacs causes a restart to be invoked."
  1754. (without-slime-interrupts
  1755. (cond (*emacs-connection*
  1756. (debug-in-emacs condition))
  1757. ((default-connection)
  1758. (with-connection ((default-connection))
  1759. (debug-in-emacs condition))))))
  1760. (define-condition invoke-default-debugger () ())
  1761. (defun swank-debugger-hook (condition hook)
  1762. "Debugger function for binding *DEBUGGER-HOOK*."
  1763. (declare (ignore hook))
  1764. (handler-case
  1765. (call-with-debugger-hook #'swank-debugger-hook
  1766. (lambda () (invoke-slime-debugger condition)))
  1767. (invoke-default-debugger ()
  1768. (invoke-default-debugger condition))))
  1769. (defun invoke-default-debugger (condition)
  1770. (call-with-debugger-hook nil (lambda () (invoke-debugger condition))))
  1771. (defvar *global-debugger* t
  1772. "Non-nil means the Swank debugger hook will be installed globally.")
  1773. (add-hook *new-connection-hook* 'install-debugger)
  1774. (defun install-debugger (connection)
  1775. (declare (ignore connection))
  1776. (when *global-debugger*
  1777. (install-debugger-globally #'swank-debugger-hook)))
  1778. ;;;;; Debugger loop
  1779. ;;;
  1780. ;;; These variables are dynamically bound during debugging.
  1781. ;;;
  1782. (defvar *swank-debugger-condition* nil
  1783. "The condition being debugged.")
  1784. (defvar *sldb-level* 0
  1785. "The current level of recursive debugging.")
  1786. (defvar *sldb-initial-frames* 20
  1787. "The initial number of backtrace frames to send to Emacs.")
  1788. (defvar *sldb-restarts* nil
  1789. "The list of currenlty active restarts.")
  1790. (defvar *sldb-stepping-p* nil
  1791. "True during execution of a step command.")
  1792. (defun debug-in-emacs (condition)
  1793. (let ((*swank-debugger-condition* condition)
  1794. (*sldb-restarts* (compute-restarts condition))
  1795. (*sldb-quit-restart* (and *sldb-quit-restart*
  1796. (find-restart *sldb-quit-restart*)))
  1797. (*package* (or (and (boundp '*buffer-package*)
  1798. (symbol-value '*buffer-package*))
  1799. *package*))
  1800. (*sldb-level* (1+ *sldb-level*))
  1801. (*sldb-stepping-p* nil))
  1802. (force-user-output)
  1803. (call-with-debugging-environment
  1804. (lambda ()
  1805. (sldb-loop *sldb-level*)))))
  1806. (defun sldb-loop (level)
  1807. (unwind-protect
  1808. (loop
  1809. (with-simple-restart (abort "Return to sldb level ~D." level)
  1810. (send-to-emacs
  1811. (list* :debug (current-thread-id) level
  1812. (debugger-info-for-emacs 0 *sldb-initial-frames*)))
  1813. (send-to-emacs
  1814. (list :debug-activate (current-thread-id) level nil))
  1815. (loop
  1816. (handler-case
  1817. (dcase (wait-for-event
  1818. `(or (:emacs-rex . _)
  1819. (:sldb-return ,(1+ level))))
  1820. ((:emacs-rex &rest args) (apply #'eval-for-emacs args))
  1821. ((:sldb-return _) (declare (ignore _)) (return nil)))
  1822. (sldb-condition (c)
  1823. (handle-sldb-condition c))))))
  1824. (send-to-emacs `(:debug-return
  1825. ,(current-thread-id) ,level ,*sldb-stepping-p*))
  1826. (wait-for-event `(:sldb-return ,(1+ level)) t) ; clean event-queue
  1827. (when (> level 1)
  1828. (send-event (current-thread) `(:sldb-return ,level)))))
  1829. (defun handle-sldb-condition (condition)
  1830. "Handle an internal debugger condition.
  1831. Rather than recursively debug the debugger (a dangerous idea!), these
  1832. conditions are simply reported."
  1833. (let ((real-condition (original-condition condition)))
  1834. (send-to-emacs `(:debug-condition ,(current-thread-id)
  1835. ,(princ-to-string real-condition)))))
  1836. (defun %%condition-message (condition)
  1837. (let ((limit (ash 1 16)))
  1838. (with-string-stream (stream :length limit)
  1839. (handler-case
  1840. (let ((*print-readably* nil)
  1841. (*print-pretty* t)
  1842. (*print-right-margin* 65)
  1843. (*print-circle* t)
  1844. (*print-length* (or *print-length* limit))
  1845. (*print-level* (or *print-level* limit))
  1846. (*print-lines* (or *print-lines* limit)))
  1847. (print-condition condition stream))
  1848. (serious-condition (c)
  1849. (ignore-errors
  1850. (with-standard-io-syntax
  1851. (let ((*print-readably* nil))
  1852. (format stream "~&Error (~a) during printing: " (type-of c))
  1853. (print-unreadable-object (condition stream :type t
  1854. :identity t))))))))))
  1855. (defun %condition-message (condition)
  1856. (string-trim #(#\newline #\space #\tab)
  1857. (%%condition-message condition)))
  1858. (defvar *sldb-condition-printer* #'%condition-message
  1859. "Function called to print a condition to an SLDB buffer.")
  1860. (defun safe-condition-message (condition)
  1861. "Print condition to a string, handling any errors during printing."
  1862. (funcall *sldb-condition-printer* condition))
  1863. (defun debugger-condition-for-emacs ()
  1864. (list (safe-condition-message *swank-debugger-condition*)
  1865. (format nil " [Condition of type ~S]"
  1866. (type-of *swank-debugger-condition*))
  1867. (condition-extras *swank-debugger-condition*)))
  1868. (defun format-restarts-for-emacs ()
  1869. "Return a list of restarts for *swank-debugger-condition* in a
  1870. format suitable for Emacs."
  1871. (let ((*print-right-margin* most-positive-fixnum))
  1872. (loop for restart in *sldb-restarts* collect
  1873. (list (format nil "~:[~;*~]~a"
  1874. (eq restart *sldb-quit-restart*)
  1875. (restart-name restart))
  1876. (with-output-to-string (stream)
  1877. (without-printing-errors (:object restart
  1878. :stream stream
  1879. :msg "<<error printing restart>>")
  1880. (princ restart stream)))))))
  1881. ;;;;; SLDB entry points
  1882. (defslimefun sldb-break-with-default-debugger (dont-unwind)
  1883. "Invoke the default debugger."
  1884. (cond (dont-unwind
  1885. (invoke-default-debugger *swank-debugger-condition*))
  1886. (t
  1887. (signal 'invoke-default-debugger))))
  1888. (defslimefun backtrace (start end)
  1889. "Return a list ((I FRAME PLIST) ...) of frames from START to END.
  1890. I is an integer, and can be used to reference the corresponding frame
  1891. from Emacs; FRAME is a string representation of an implementation's
  1892. frame."
  1893. (loop for frame in (compute-backtrace start end)
  1894. for i from start collect
  1895. (list* i (frame-to-string frame)
  1896. (ecase (frame-restartable-p frame)
  1897. ((nil) nil)
  1898. ((t) `((:restartable t)))))))
  1899. (defun frame-to-string (frame)
  1900. (with-string-stream (stream :length (* (or *print-lines* 1)
  1901. (or *print-right-margin* 100))
  1902. :bindings *backtrace-printer-bindings*)
  1903. (handler-case (print-frame frame stream)
  1904. (serious-condition ()
  1905. (format stream "[error printing frame]")))))
  1906. (defslimefun debugger-info-for-emacs (start end)
  1907. "Return debugger state, with stack frames from START to END.
  1908. The result is a list:
  1909. (condition ({restart}*) ({stack-frame}*) (cont*))
  1910. where
  1911. condition ::= (description type [extra])
  1912. restart ::= (name description)
  1913. stack-frame ::= (number description [plist])
  1914. extra ::= (:references and other random things)
  1915. cont ::= continutation
  1916. plist ::= (:restartable {nil | t | :unknown})
  1917. condition---a pair of strings: message, and type. If show-source is
  1918. not nil it is a frame number for which the source should be displayed.
  1919. restart---a pair of strings: restart name, and description.
  1920. stack-frame---a number from zero (the top), and a printed
  1921. representation of the frame's call.
  1922. continutation---the id of a pending Emacs continuation.
  1923. Below is an example return value. In this case the condition was a
  1924. division by zero (multi-line description), and only one frame is being
  1925. fetched (start=0, end=1).
  1926. ((\"Arithmetic error DIVISION-BY-ZERO signalled.
  1927. Operation was KERNEL::DIVISION, operands (1 0).\"
  1928. \"[Condition of type DIVISION-BY-ZERO]\")
  1929. ((\"ABORT\" \"Return to Slime toplevel.\")
  1930. (\"ABORT\" \"Return to Top-Level.\"))
  1931. ((0 \"(KERNEL::INTEGER-/-INTEGER 1 0)\" (:restartable nil)))
  1932. (4))"
  1933. (list (debugger-condition-for-emacs)
  1934. (format-restarts-for-emacs)
  1935. (backtrace start end)
  1936. *pending-continuations*))
  1937. (defun nth-restart (index)
  1938. (nth index *sldb-restarts*))
  1939. (defslimefun invoke-nth-restart (index)
  1940. (let ((restart (nth-restart index)))
  1941. (when restart
  1942. (invoke-restart-interactively restart))))
  1943. (defslimefun sldb-abort ()
  1944. (invoke-restart (find 'abort *sldb-restarts* :key #'restart-name)))
  1945. (defslimefun sldb-continue ()
  1946. (continue))
  1947. (defun coerce-to-condition (datum args)
  1948. (etypecase datum
  1949. (string (make-condition 'simple-error :format-control datum
  1950. :format-arguments args))
  1951. (symbol (apply #'make-condition datum args))))
  1952. (defslimefun simple-break (&optional (datum "Interrupt from Emacs") &rest args)
  1953. (with-simple-restart (continue "Continue from break.")
  1954. (invoke-slime-debugger (coerce-to-condition datum args))))
  1955. ;; FIXME: (last (compute-restarts)) looks dubious.
  1956. (defslimefun throw-to-toplevel ()
  1957. "Invoke the ABORT-REQUEST restart abort an RPC from Emacs.
  1958. If we are not evaluating an RPC then ABORT instead."
  1959. (let ((restart (or (and *sldb-quit-restart*
  1960. (find-restart *sldb-quit-restart*))
  1961. (car (last (compute-restarts))))))
  1962. (cond (restart (invoke-restart restart))
  1963. (t (format nil "Restart not active [~s]" *sldb-quit-restart*)))))
  1964. (defslimefun invoke-nth-restart-for-emacs (sldb-level n)
  1965. "Invoke the Nth available restart.
  1966. SLDB-LEVEL is the debug level when the request was made. If this
  1967. has changed, ignore the request."
  1968. (when (= sldb-level *sldb-level*)
  1969. (invoke-nth-restart n)))
  1970. (defun wrap-sldb-vars (form)
  1971. `(let ((*sldb-level* ,*sldb-level*))
  1972. ,form))
  1973. (defun eval-in-frame-aux (frame string package print)
  1974. (let* ((form (wrap-sldb-vars (parse-string string package)))
  1975. (values (multiple-value-list (eval-in-frame form frame))))
  1976. (with-buffer-syntax (package)
  1977. (funcall print values))))
  1978. (defslimefun eval-string-in-frame (string frame package)
  1979. (eval-in-frame-aux frame string package #'format-values-for-echo-area))
  1980. (defslimefun pprint-eval-string-in-frame (string frame package)
  1981. (eval-in-frame-aux frame string package #'swank-pprint))
  1982. (defslimefun frame-package-name (frame)
  1983. (let ((pkg (frame-package frame)))
  1984. (cond (pkg (package-name pkg))
  1985. (t (with-buffer-syntax () (package-name *package*))))))
  1986. (defslimefun frame-locals-and-catch-tags (index)
  1987. "Return a list (LOCALS TAGS) for vars and catch tags in the frame INDEX.
  1988. LOCALS is a list of the form ((&key NAME ID VALUE) ...).
  1989. TAGS has is a list of strings."
  1990. (list (frame-locals-for-emacs index)
  1991. (mapcar #'to-string (frame-catch-tags index))))
  1992. (defun frame-locals-for-emacs (index)
  1993. (with-bindings *backtrace-printer-bindings*
  1994. (loop for var in (frame-locals index) collect
  1995. (destructuring-bind (&key name id value) var
  1996. (list :name (let ((*package* (or (frame-package index) *package*)))
  1997. (prin1-to-string name))
  1998. :id id
  1999. :value (to-line value *print-right-margin*))))))
  2000. (defslimefun sldb-disassemble (index)
  2001. (with-output-to-string (*standard-output*)
  2002. (disassemble-frame index)))
  2003. (defslimefun sldb-return-from-frame (index string)
  2004. (let ((form (from-string string)))
  2005. (to-string (multiple-value-list (return-from-frame index form)))))
  2006. (defslimefun sldb-break (name)
  2007. (with-buffer-syntax ()
  2008. (sldb-break-at-start (read-from-string name))))
  2009. (defmacro define-stepper-function (name backend-function-name)
  2010. `(defslimefun ,name (frame)
  2011. (cond ((sldb-stepper-condition-p *swank-debugger-condition*)
  2012. (setq *sldb-stepping-p* t)
  2013. (,backend-function-name))
  2014. ((find-restart 'continue)
  2015. (activate-stepping frame)
  2016. (setq *sldb-stepping-p* t)
  2017. (continue))
  2018. (t
  2019. (error "Not currently single-stepping, ~
  2020. and no continue restart available.")))))
  2021. (define-stepper-function sldb-step sldb-step-into)
  2022. (define-stepper-function sldb-next sldb-step-next)
  2023. (define-stepper-function sldb-out sldb-step-out)
  2024. (defslimefun toggle-break-on-signals ()
  2025. (setq *break-on-signals* (not *break-on-signals*))
  2026. (format nil "*break-on-signals* = ~a" *break-on-signals*))
  2027. (defslimefun sdlb-print-condition ()
  2028. (princ-to-string *swank-debugger-condition*))
  2029. ;;;; Compilation Commands.
  2030. (defstruct (compilation-result (:type list))
  2031. (type :compilation-result)
  2032. notes
  2033. (successp nil :type boolean)
  2034. (duration 0.0 :type float)
  2035. (loadp nil :type boolean)
  2036. (faslfile nil :type (or null string)))
  2037. (defun measure-time-interval (fun)
  2038. "Call FUN and return the first return value and the elapsed time.
  2039. The time is measured in seconds."
  2040. (declare (type function fun))
  2041. (let ((before (get-internal-real-time)))
  2042. (values
  2043. (funcall fun)
  2044. (/ (- (get-internal-real-time) before)
  2045. (coerce internal-time-units-per-second 'float)))))
  2046. (defun make-compiler-note (condition)
  2047. "Make a compiler note data structure from a compiler-condition."
  2048. (declare (type compiler-condition condition))
  2049. (list* :message (message condition)
  2050. :severity (severity condition)
  2051. :location (location condition)
  2052. :references (references condition)
  2053. (let ((s (source-context condition)))
  2054. (if s (list :source-context s)))))
  2055. (defun collect-notes (function)
  2056. (let ((notes '()))
  2057. (multiple-value-bind (result seconds)
  2058. (handler-bind ((compiler-condition
  2059. (lambda (c) (push (make-compiler-note c) notes))))
  2060. (measure-time-interval
  2061. (lambda ()
  2062. ;; To report location of error-signaling toplevel forms
  2063. ;; for errors in EVAL-WHEN or during macroexpansion.
  2064. (restart-case (multiple-value-list (funcall function))
  2065. (abort () :report "Abort compilation." (list nil))))))
  2066. (destructuring-bind (successp &optional loadp faslfile) result
  2067. (let ((faslfile (etypecase faslfile
  2068. (null nil)
  2069. (pathname (pathname-to-filename faslfile)))))
  2070. (make-compilation-result :notes (reverse notes)
  2071. :duration seconds
  2072. :successp (if successp t)
  2073. :loadp (if loadp t)
  2074. :faslfile faslfile))))))
  2075. (defun swank-compile-file* (pathname load-p &rest options &key policy
  2076. &allow-other-keys)
  2077. (multiple-value-bind (output-pathname warnings? failure?)
  2078. (swank-compile-file pathname
  2079. (fasl-pathname pathname options)
  2080. nil
  2081. (or (guess-external-format pathname)
  2082. :default)
  2083. :policy policy)
  2084. (declare (ignore warnings?))
  2085. (values t (not failure?) load-p output-pathname)))
  2086. (defvar *compile-file-for-emacs-hook* '(swank-compile-file*))
  2087. (defslimefun compile-file-for-emacs (filename load-p &rest options)
  2088. "Compile FILENAME and, when LOAD-P, load the result.
  2089. Record compiler notes signalled as `compiler-condition's."
  2090. (with-buffer-syntax ()
  2091. (collect-notes
  2092. (lambda ()
  2093. (let ((pathname (filename-to-pathname filename))
  2094. (*compile-print* nil)
  2095. (*compile-verbose* t))
  2096. (loop for hook in *compile-file-for-emacs-hook*
  2097. do
  2098. (multiple-value-bind (tried success load? output-pathname)
  2099. (apply hook pathname load-p options)
  2100. (when tried
  2101. (return (values success load? output-pathname))))))))))
  2102. ;; FIXME: now that *compile-file-for-emacs-hook* is there this is
  2103. ;; redundant and confusing.
  2104. (defvar *fasl-pathname-function* nil
  2105. "In non-nil, use this function to compute the name for fasl-files.")
  2106. (defun pathname-as-directory (pathname)
  2107. (append (pathname-directory pathname)
  2108. (when (pathname-name pathname)
  2109. (list (file-namestring pathname)))))
  2110. (defun compile-file-output (file directory)
  2111. (make-pathname :directory (pathname-as-directory directory)
  2112. :defaults (compile-file-pathname file)))
  2113. (defun fasl-pathname (input-file options)
  2114. (cond (*fasl-pathname-function*
  2115. (funcall *fasl-pathname-function* input-file options))
  2116. ((getf options :fasl-directory)
  2117. (let ((dir (getf options :fasl-directory)))
  2118. (assert (char= (aref dir (1- (length dir))) #\/))
  2119. (compile-file-output input-file dir)))
  2120. (t
  2121. (compile-file-pathname input-file))))
  2122. (defslimefun compile-string-for-emacs (string buffer position filename policy)
  2123. "Compile STRING (exerpted from BUFFER at POSITION).
  2124. Record compiler notes signalled as `compiler-condition's."
  2125. (let ((offset (cadr (assoc :position position))))
  2126. (with-buffer-syntax ()
  2127. (collect-notes
  2128. (lambda ()
  2129. (let ((*compile-print* t) (*compile-verbose* nil))
  2130. (swank-compile-string string
  2131. :buffer buffer
  2132. :position offset
  2133. :filename filename
  2134. :policy policy)))))))
  2135. (defslimefun compile-multiple-strings-for-emacs (strings policy)
  2136. "Compile STRINGS (exerpted from BUFFER at POSITION).
  2137. Record compiler notes signalled as `compiler-condition's."
  2138. (loop for (string buffer package position filename) in strings collect
  2139. (collect-notes
  2140. (lambda ()
  2141. (with-buffer-syntax (package)
  2142. (let ((*compile-print* t) (*compile-verbose* nil))
  2143. (swank-compile-string string
  2144. :buffer buffer
  2145. :position position
  2146. :filename filename
  2147. :policy policy)))))))
  2148. (defun file-newer-p (new-file old-file)
  2149. "Returns true if NEW-FILE is newer than OLD-FILE."
  2150. (> (file-write-date new-file) (file-write-date old-file)))
  2151. (defun requires-compile-p (source-file)
  2152. (let ((fasl-file (probe-file (compile-file-pathname source-file))))
  2153. (or (not fasl-file)
  2154. (file-newer-p source-file fasl-file))))
  2155. (defslimefun compile-file-if-needed (filename loadp)
  2156. (let ((pathname (filename-to-pathname filename)))
  2157. (cond ((requires-compile-p pathname)
  2158. (compile-file-for-emacs pathname loadp))
  2159. (t
  2160. (collect-notes
  2161. (lambda ()
  2162. (or (not loadp)
  2163. (load (compile-file-pathname pathname)))))))))
  2164. ;;;; Loading
  2165. (defslimefun load-file (filename)
  2166. (to-string (load (filename-to-pathname filename))))
  2167. ;;;;; swank-require
  2168. (defslimefun swank-require (modules &optional filename)
  2169. "Load the module MODULE."
  2170. (dolist (module (ensure-list modules))
  2171. (unless (member (string module) *modules* :test #'string=)
  2172. (require module (if filename
  2173. (filename-to-pathname filename)
  2174. (module-filename module)))
  2175. (assert (member (string module) *modules* :test #'string=)
  2176. () "Required module ~s was not provided" module)))
  2177. *modules*)
  2178. (defvar *find-module* 'find-module
  2179. "Pluggable function to locate modules.
  2180. The function receives a module name as argument and should return
  2181. the filename of the module (or nil if the file doesn't exist).")
  2182. (defun module-filename (module)
  2183. "Return the filename for the module MODULE."
  2184. (or (funcall *find-module* module)
  2185. (error "Can't locate module: ~s" module)))
  2186. ;;;;;; Simple *find-module* function.
  2187. (defun merged-directory (dirname defaults)
  2188. (pathname-directory
  2189. (merge-pathnames
  2190. (make-pathname :directory `(:relative ,dirname) :defaults defaults)
  2191. defaults)))
  2192. (defvar *load-path* '()
  2193. "A list of directories to search for modules.")
  2194. (defun module-candidates (name dir)
  2195. (list (compile-file-pathname (make-pathname :name name :defaults dir))
  2196. (make-pathname :name name :type "lisp" :defaults dir)))
  2197. (defun find-module (module)
  2198. (let ((name (string-downcase module)))
  2199. (some (lambda (dir) (some #'probe-file (module-candidates name dir)))
  2200. *load-path*)))
  2201. ;;;; Macroexpansion
  2202. (defvar *macroexpand-printer-bindings*
  2203. '((*print-circle* . nil)
  2204. (*print-pretty* . t)
  2205. (*print-escape* . t)
  2206. (*print-lines* . nil)
  2207. (*print-level* . nil)
  2208. (*print-length* . nil)))
  2209. (defun apply-macro-expander (expander string)
  2210. (with-buffer-syntax ()
  2211. (with-bindings *macroexpand-printer-bindings*
  2212. (prin1-to-string (funcall expander (from-string string))))))
  2213. (defslimefun swank-macroexpand-1 (string)
  2214. (apply-macro-expander #'macroexpand-1 string))
  2215. (defslimefun swank-macroexpand (string)
  2216. (apply-macro-expander #'macroexpand string))
  2217. (defslimefun swank-macroexpand-all (string)
  2218. (apply-macro-expander #'macroexpand-all string))
  2219. (defslimefun swank-compiler-macroexpand-1 (string)
  2220. (apply-macro-expander #'compiler-macroexpand-1 string))
  2221. (defslimefun swank-compiler-macroexpand (string)
  2222. (apply-macro-expander #'compiler-macroexpand string))
  2223. (defslimefun swank-expand-1 (string)
  2224. (apply-macro-expander #'expand-1 string))
  2225. (defslimefun swank-expand (string)
  2226. (apply-macro-expander #'expand string))
  2227. (defun expand-1 (form)
  2228. (multiple-value-bind (expansion expanded?) (macroexpand-1 form)
  2229. (if expanded?
  2230. (values expansion t)
  2231. (compiler-macroexpand-1 form))))
  2232. (defun expand (form)
  2233. (expand-repeatedly #'expand-1 form))
  2234. (defun expand-repeatedly (expander form)
  2235. (loop
  2236. (multiple-value-bind (expansion expanded?) (funcall expander form)
  2237. (unless expanded? (return expansion))
  2238. (setq form expansion))))
  2239. (defslimefun swank-format-string-expand (string)
  2240. (apply-macro-expander #'format-string-expand string))
  2241. (defslimefun disassemble-form (form)
  2242. (with-buffer-syntax ()
  2243. (with-output-to-string (*standard-output*)
  2244. (let ((*print-readably* nil))
  2245. (disassemble (eval (read-from-string form)))))))
  2246. ;;;; Simple completion
  2247. (defslimefun simple-completions (prefix package)
  2248. "Return a list of completions for the string PREFIX."
  2249. (let ((strings (all-completions prefix package)))
  2250. (list strings (longest-common-prefix strings))))
  2251. (defun all-completions (prefix package)
  2252. (multiple-value-bind (name pname intern) (tokenize-symbol prefix)
  2253. (let* ((extern (and pname (not intern)))
  2254. (pkg (cond ((equal pname "") keyword-package)
  2255. ((not pname) (guess-buffer-package package))
  2256. (t (guess-package pname))))
  2257. (test (lambda (sym) (prefix-match-p name (symbol-name sym))))
  2258. (syms (and pkg (matching-symbols pkg extern test)))
  2259. (strings (loop for sym in syms
  2260. for str = (unparse-symbol sym)
  2261. when (prefix-match-p name str) ; remove |Foo|
  2262. collect str)))
  2263. (format-completion-set strings intern pname))))
  2264. (defun matching-symbols (package external test)
  2265. (let ((test (if external
  2266. (lambda (s)
  2267. (and (symbol-external-p s package)
  2268. (funcall test s)))
  2269. test))
  2270. (result '()))
  2271. (do-symbols (s package)
  2272. (when (funcall test s)
  2273. (push s result)))
  2274. (remove-duplicates result)))
  2275. (defun unparse-symbol (symbol)
  2276. (let ((*print-case* (case (readtable-case *readtable*)
  2277. (:downcase :upcase)
  2278. (t :downcase))))
  2279. (unparse-name (symbol-name symbol))))
  2280. (defun prefix-match-p (prefix string)
  2281. "Return true if PREFIX is a prefix of STRING."
  2282. (not (mismatch prefix string :end2 (min (length string) (length prefix))
  2283. :test #'char-equal)))
  2284. (defun longest-common-prefix (strings)
  2285. "Return the longest string that is a common prefix of STRINGS."
  2286. (if (null strings)
  2287. ""
  2288. (flet ((common-prefix (s1 s2)
  2289. (let ((diff-pos (mismatch s1 s2)))
  2290. (if diff-pos (subseq s1 0 diff-pos) s1))))
  2291. (reduce #'common-prefix strings))))
  2292. (defun format-completion-set (strings internal-p package-name)
  2293. "Format a set of completion strings.
  2294. Returns a list of completions with package qualifiers if needed."
  2295. (mapcar (lambda (string) (untokenize-symbol package-name internal-p string))
  2296. (sort strings #'string<)))
  2297. ;;;; Simple arglist display
  2298. (defslimefun operator-arglist (name package)
  2299. (ignore-errors
  2300. (let ((args (arglist (parse-symbol name (guess-buffer-package package)))))
  2301. (cond ((eq args :not-available) nil)
  2302. (t (princ-to-string (cons name args)))))))
  2303. ;;;; Documentation
  2304. (defslimefun apropos-list-for-emacs (name &optional external-only
  2305. case-sensitive package)
  2306. "Make an apropos search for Emacs.
  2307. The result is a list of property lists."
  2308. (let ((package (if package
  2309. (or (parse-package package)
  2310. (error "No such package: ~S" package)))))
  2311. ;; The MAPCAN will filter all uninteresting symbols, i.e. those
  2312. ;; who cannot be meaningfully described.
  2313. (mapcan (listify #'briefly-describe-symbol-for-emacs)
  2314. (sort (remove-duplicates
  2315. (apropos-symbols name external-only case-sensitive package))
  2316. #'present-symbol-before-p))))
  2317. (defun briefly-describe-symbol-for-emacs (symbol)
  2318. "Return a property list describing SYMBOL.
  2319. Like `describe-symbol-for-emacs' but with at most one line per item."
  2320. (flet ((first-line (string)
  2321. (let ((pos (position #\newline string)))
  2322. (if (null pos) string (subseq string 0 pos)))))
  2323. (let ((desc (map-if #'stringp #'first-line
  2324. (describe-symbol-for-emacs symbol))))
  2325. (if desc
  2326. (list* :designator (to-string symbol) desc)))))
  2327. (defun map-if (test fn &rest lists)
  2328. "Like (mapcar FN . LISTS) but only call FN on objects satisfying TEST.
  2329. Example:
  2330. \(map-if #'oddp #'- '(1 2 3 4 5)) => (-1 2 -3 4 -5)"
  2331. (apply #'mapcar
  2332. (lambda (x) (if (funcall test x) (funcall fn x) x))
  2333. lists))
  2334. (defun listify (f)
  2335. "Return a function like F, but which returns any non-null value
  2336. wrapped in a list."
  2337. (lambda (x)
  2338. (let ((y (funcall f x)))
  2339. (and y (list y)))))
  2340. (defun present-symbol-before-p (x y)
  2341. "Return true if X belongs before Y in a printed summary of symbols.
  2342. Sorted alphabetically by package name and then symbol name, except
  2343. that symbols accessible in the current package go first."
  2344. (declare (type symbol x y))
  2345. (flet ((accessible (s)
  2346. ;; Test breaks on NIL for package that does not inherit it
  2347. (eq (find-symbol (symbol-name s) *buffer-package*) s)))
  2348. (let ((ax (accessible x)) (ay (accessible y)))
  2349. (cond ((and ax ay) (string< (symbol-name x) (symbol-name y)))
  2350. (ax t)
  2351. (ay nil)
  2352. (t (let ((px (symbol-package x)) (py (symbol-package y)))
  2353. (if (eq px py)
  2354. (string< (symbol-name x) (symbol-name y))
  2355. (string< (package-name px) (package-name py)))))))))
  2356. (defun make-apropos-matcher (pattern case-sensitive)
  2357. (let ((chr= (if case-sensitive #'char= #'char-equal)))
  2358. (lambda (symbol)
  2359. (search pattern (string symbol) :test chr=))))
  2360. (defun apropos-symbols (string external-only case-sensitive package)
  2361. (let ((packages (or package (remove (find-package :keyword)
  2362. (list-all-packages))))
  2363. (matcher (make-apropos-matcher string case-sensitive))
  2364. (result))
  2365. (with-package-iterator (next packages :external :internal)
  2366. (loop (multiple-value-bind (morep symbol) (next)
  2367. (cond ((not morep) (return))
  2368. ((and (if external-only (symbol-external-p symbol) t)
  2369. (funcall matcher symbol))
  2370. (push symbol result))))))
  2371. result))
  2372. (defun call-with-describe-settings (fn)
  2373. (let ((*print-readably* nil))
  2374. (funcall fn)))
  2375. (defmacro with-describe-settings ((&rest _) &body body)
  2376. (declare (ignore _))
  2377. `(call-with-describe-settings (lambda () ,@body)))
  2378. (defun describe-to-string (object)
  2379. (with-describe-settings ()
  2380. (with-output-to-string (*standard-output*)
  2381. (describe object))))
  2382. (defslimefun describe-symbol (symbol-name)
  2383. (with-buffer-syntax ()
  2384. (describe-to-string (parse-symbol-or-lose symbol-name))))
  2385. (defslimefun describe-function (name)
  2386. (with-buffer-syntax ()
  2387. (let ((symbol (parse-symbol-or-lose name)))
  2388. (describe-to-string (or (macro-function symbol)
  2389. (symbol-function symbol))))))
  2390. (defslimefun describe-definition-for-emacs (name kind)
  2391. (with-buffer-syntax ()
  2392. (with-describe-settings ()
  2393. (with-output-to-string (*standard-output*)
  2394. (describe-definition (parse-symbol-or-lose name) kind)))))
  2395. (defslimefun documentation-symbol (symbol-name)
  2396. (with-buffer-syntax ()
  2397. (multiple-value-bind (sym foundp) (parse-symbol symbol-name)
  2398. (if foundp
  2399. (let ((vdoc (documentation sym 'variable))
  2400. (fdoc (documentation sym 'function)))
  2401. (with-output-to-string (string)
  2402. (format string "Documentation for the symbol ~a:~2%" sym)
  2403. (unless (or vdoc fdoc)
  2404. (format string "Not documented." ))
  2405. (when vdoc
  2406. (format string "Variable:~% ~a~2%" vdoc))
  2407. (when fdoc
  2408. (format string "Function:~% Arglist: ~a~2% ~a"
  2409. (arglist sym)
  2410. fdoc))))
  2411. (format nil "No such symbol, ~a." symbol-name)))))
  2412. ;;;; Package Commands
  2413. (defslimefun list-all-package-names (&optional nicknames)
  2414. "Return a list of all package names.
  2415. Include the nicknames if NICKNAMES is true."
  2416. (mapcar #'unparse-name
  2417. (if nicknames
  2418. (mapcan #'package-names (list-all-packages))
  2419. (mapcar #'package-name (list-all-packages)))))
  2420. ;;;; Tracing
  2421. ;; Use eval for the sake of portability...
  2422. (defun tracedp (fspec)
  2423. (member fspec (eval '(trace))))
  2424. (defvar *after-toggle-trace-hook* nil
  2425. "Hook called whenever a SPEC is traced or untraced.
  2426. If non-nil, called with two arguments SPEC and TRACED-P." )
  2427. (defslimefun swank-toggle-trace (spec-string)
  2428. (let* ((spec (from-string spec-string))
  2429. (retval (cond ((consp spec) ; handle complicated cases in the backend
  2430. (toggle-trace spec))
  2431. ((tracedp spec)
  2432. (eval `(untrace ,spec))
  2433. (format nil "~S is now untraced." spec))
  2434. (t
  2435. (eval `(trace ,spec))
  2436. (format nil "~S is now traced." spec))))
  2437. (traced-p (let* ((tosearch "is now traced.")
  2438. (start (- (length retval)
  2439. (length tosearch)))
  2440. (end (+ start (length tosearch))))
  2441. (search tosearch (subseq retval start end))))
  2442. (hook-msg (when *after-toggle-trace-hook*
  2443. (funcall *after-toggle-trace-hook*
  2444. spec
  2445. traced-p))))
  2446. (if hook-msg
  2447. (format nil "~a~%(also ~a)" retval hook-msg)
  2448. retval)))
  2449. (defslimefun untrace-all ()
  2450. (untrace))
  2451. ;;;; Undefing
  2452. (defslimefun undefine-function (fname-string)
  2453. (let ((fname (from-string fname-string)))
  2454. (format nil "~S" (fmakunbound fname))))
  2455. (defslimefun unintern-symbol (name package)
  2456. (let ((pkg (guess-package package)))
  2457. (cond ((not pkg) (format nil "No such package: ~s" package))
  2458. (t
  2459. (multiple-value-bind (sym found) (parse-symbol name pkg)
  2460. (case found
  2461. ((nil) (format nil "~s not in package ~s" name package))
  2462. (t
  2463. (unintern sym pkg)
  2464. (format nil "Uninterned symbol: ~s" sym))))))))
  2465. (defslimefun swank-delete-package (package-name)
  2466. (let ((pkg (or (guess-package package-name)
  2467. (error "No such package: ~s" package-name))))
  2468. (delete-package pkg)
  2469. nil))
  2470. ;;;; Profiling
  2471. (defun profiledp (fspec)
  2472. (member fspec (profiled-functions)))
  2473. (defslimefun toggle-profile-fdefinition (fname-string)
  2474. (let ((fname (from-string fname-string)))
  2475. (cond ((profiledp fname)
  2476. (unprofile fname)
  2477. (format nil "~S is now unprofiled." fname))
  2478. (t
  2479. (profile fname)
  2480. (format nil "~S is now profiled." fname)))))
  2481. (defslimefun profile-by-substring (substring package)
  2482. (let ((count 0))
  2483. (flet ((maybe-profile (symbol)
  2484. (when (and (fboundp symbol)
  2485. (not (profiledp symbol))
  2486. (search substring (symbol-name symbol) :test #'equalp))
  2487. (handler-case (progn
  2488. (profile symbol)
  2489. (incf count))
  2490. (error (condition)
  2491. (warn "~a" condition))))))
  2492. (if package
  2493. (do-symbols (symbol (parse-package package))
  2494. (maybe-profile symbol))
  2495. (do-all-symbols (symbol)
  2496. (maybe-profile symbol))))
  2497. (format nil "~a function~:p ~:*~[are~;is~:;are~] now profiled" count)))
  2498. (defslimefun swank-profile-package (package-name callersp methodsp)
  2499. (let ((pkg (or (guess-package package-name)
  2500. (error "Not a valid package name: ~s" package-name))))
  2501. (check-type callersp boolean)
  2502. (check-type methodsp boolean)
  2503. (profile-package pkg callersp methodsp)))
  2504. ;;;; Source Locations
  2505. (defslimefun find-definition-for-thing (thing)
  2506. (find-source-location thing))
  2507. (defslimefun find-source-location-for-emacs (spec)
  2508. (find-source-location (value-spec-ref spec)))
  2509. (defun value-spec-ref (spec)
  2510. (dcase spec
  2511. ((:string string package)
  2512. (with-buffer-syntax (package)
  2513. (eval (read-from-string string))))
  2514. ((:inspector part)
  2515. (inspector-nth-part part))
  2516. ((:sldb frame var)
  2517. (frame-var-value frame var))))
  2518. (defvar *find-definitions-right-trim* ",:.>")
  2519. (defvar *find-definitions-left-trim* "#:<")
  2520. (defun find-definitions-find-symbol-or-package (name)
  2521. (flet ((do-find (name)
  2522. (multiple-value-bind (symbol found name)
  2523. (with-buffer-syntax ()
  2524. (parse-symbol name))
  2525. (cond (found
  2526. (return-from find-definitions-find-symbol-or-package
  2527. (values symbol found)))
  2528. ;; Packages are not named by symbols, so
  2529. ;; not-interned symbols can refer to packages
  2530. ((find-package name)
  2531. (return-from find-definitions-find-symbol-or-package
  2532. (values (make-symbol name) t)))))))
  2533. (do-find name)
  2534. (do-find (string-right-trim *find-definitions-right-trim* name))
  2535. (do-find (string-left-trim *find-definitions-left-trim* name))
  2536. (do-find (string-left-trim *find-definitions-left-trim*
  2537. (string-right-trim
  2538. *find-definitions-right-trim* name)))
  2539. ;; Not exactly robust
  2540. (when (and (eql (search "(setf " name :test #'char-equal) 0)
  2541. (char= (char name (1- (length name))) #\)))
  2542. (multiple-value-bind (symbol found)
  2543. (with-buffer-syntax ()
  2544. (parse-symbol (subseq name (length "(setf ")
  2545. (1- (length name)))))
  2546. (when found
  2547. (values `(setf ,symbol) t))))))
  2548. (defslimefun find-definitions-for-emacs (name)
  2549. "Return a list ((DSPEC LOCATION) ...) of definitions for NAME.
  2550. DSPEC is a string and LOCATION a source location. NAME is a string."
  2551. (multiple-value-bind (symbol found)
  2552. (find-definitions-find-symbol-or-package name)
  2553. (when found
  2554. (mapcar #'xref>elisp (find-definitions symbol)))))
  2555. ;;; Generic function so contribs can extend it.
  2556. (defgeneric xref-doit (type thing)
  2557. (:method (type thing)
  2558. (declare (ignore type thing))
  2559. :not-implemented))
  2560. (macrolet ((define-xref-action (xref-type handler)
  2561. `(defmethod xref-doit ((type (eql ,xref-type)) thing)
  2562. (declare (ignorable type))
  2563. (funcall ,handler thing))))
  2564. (define-xref-action :calls #'who-calls)
  2565. (define-xref-action :calls-who #'calls-who)
  2566. (define-xref-action :references #'who-references)
  2567. (define-xref-action :binds #'who-binds)
  2568. (define-xref-action :sets #'who-sets)
  2569. (define-xref-action :macroexpands #'who-macroexpands)
  2570. (define-xref-action :specializes #'who-specializes)
  2571. (define-xref-action :callers #'list-callers)
  2572. (define-xref-action :callees #'list-callees))
  2573. (defslimefun xref (type name)
  2574. (multiple-value-bind (sexp error) (ignore-errors (from-string name))
  2575. (unless error
  2576. (let ((xrefs (xref-doit type sexp)))
  2577. (if (eq xrefs :not-implemented)
  2578. :not-implemented
  2579. (mapcar #'xref>elisp xrefs))))))
  2580. (defslimefun xrefs (types name)
  2581. (loop for type in types
  2582. for xrefs = (xref type name)
  2583. when (and (not (eq :not-implemented xrefs))
  2584. (not (null xrefs)))
  2585. collect (cons type xrefs)))
  2586. (defun xref>elisp (xref)
  2587. (destructuring-bind (name loc) xref
  2588. (list (to-string name) loc)))
  2589. ;;;;; Lazy lists
  2590. (defstruct (lcons (:constructor %lcons (car %cdr))
  2591. (:predicate lcons?))
  2592. car
  2593. (%cdr nil :type (or null lcons function))
  2594. (forced? nil))
  2595. (defmacro lcons (car cdr)
  2596. `(%lcons ,car (lambda () ,cdr)))
  2597. (defmacro lcons* (car cdr &rest more)
  2598. (cond ((null more) `(lcons ,car ,cdr))
  2599. (t `(lcons ,car (lcons* ,cdr ,@more)))))
  2600. (defun lcons-cdr (lcons)
  2601. (with-struct* (lcons- @ lcons)
  2602. (cond ((@ forced?)
  2603. (@ %cdr))
  2604. (t
  2605. (let ((value (funcall (@ %cdr))))
  2606. (setf (@ forced?) t
  2607. (@ %cdr) value))))))
  2608. (defun llist-range (llist start end)
  2609. (llist-take (llist-skip llist start) (- end start)))
  2610. (defun llist-skip (lcons index)
  2611. (do ((i 0 (1+ i))
  2612. (l lcons (lcons-cdr l)))
  2613. ((or (= i index) (null l))
  2614. l)))
  2615. (defun llist-take (lcons count)
  2616. (let ((result '()))
  2617. (do ((i 0 (1+ i))
  2618. (l lcons (lcons-cdr l)))
  2619. ((or (= i count)
  2620. (null l)))
  2621. (push (lcons-car l) result))
  2622. (nreverse result)))
  2623. (defun iline (label value)
  2624. `(:line ,label ,value))
  2625. ;;;; Inspecting
  2626. (defvar *inspector-verbose* nil)
  2627. (defvar *inspector-printer-bindings*
  2628. '((*print-lines* . 1)
  2629. (*print-right-margin* . 75)
  2630. (*print-pretty* . t)
  2631. (*print-readably* . nil)))
  2632. (defvar *inspector-verbose-printer-bindings*
  2633. '((*print-escape* . t)
  2634. (*print-circle* . t)
  2635. (*print-array* . nil)))
  2636. (defstruct inspector-state)
  2637. (defstruct (istate (:conc-name istate.) (:include inspector-state))
  2638. object
  2639. (verbose *inspector-verbose*)
  2640. (parts (make-array 10 :adjustable t :fill-pointer 0))
  2641. (actions (make-array 10 :adjustable t :fill-pointer 0))
  2642. metadata-plist
  2643. content
  2644. next previous)
  2645. (defvar *istate* nil)
  2646. (defvar *inspector-history*)
  2647. (defun reset-inspector ()
  2648. (setq *istate* nil
  2649. *inspector-history* (make-array 10 :adjustable t :fill-pointer 0)))
  2650. (defslimefun init-inspector (string)
  2651. (with-buffer-syntax ()
  2652. (with-retry-restart (:msg "Retry SLIME inspection request.")
  2653. (reset-inspector)
  2654. (inspect-object (eval (read-from-string string))))))
  2655. (defun ensure-istate-metadata (o indicator default)
  2656. (with-struct (istate. object metadata-plist) *istate*
  2657. (assert (eq object o))
  2658. (let ((data (getf metadata-plist indicator default)))
  2659. (setf (getf metadata-plist indicator) data)
  2660. data)))
  2661. (defun inspect-object (o)
  2662. (let* ((prev *istate*)
  2663. (istate (make-istate :object o :previous prev
  2664. :verbose (cond (prev (istate.verbose prev))
  2665. (t *inspector-verbose*)))))
  2666. (setq *istate* istate)
  2667. (setf (istate.content istate) (emacs-inspect/istate istate))
  2668. (unless (find o *inspector-history*)
  2669. (vector-push-extend o *inspector-history*))
  2670. (let ((previous (istate.previous istate)))
  2671. (if previous (setf (istate.next previous) istate)))
  2672. (istate>elisp istate)))
  2673. (defun emacs-inspect/istate (istate)
  2674. (with-bindings (if (istate.verbose istate)
  2675. *inspector-verbose-printer-bindings*
  2676. *inspector-printer-bindings*)
  2677. (emacs-inspect (istate.object istate))))
  2678. (defun istate>elisp (istate)
  2679. (list :title (prepare-title istate)
  2680. :id (assign-index (istate.object istate) (istate.parts istate))
  2681. :content (prepare-range istate 0 500)))
  2682. (defun prepare-title (istate)
  2683. (if (istate.verbose istate)
  2684. (with-bindings *inspector-verbose-printer-bindings*
  2685. (to-string (istate.object istate)))
  2686. (with-string-stream (stream :length 200
  2687. :bindings *inspector-printer-bindings*)
  2688. (print-unreadable-object
  2689. ((istate.object istate) stream :type t :identity t)))))
  2690. (defun prepare-range (istate start end)
  2691. (let* ((range (content-range (istate.content istate) start end))
  2692. (ps (loop for part in range append (prepare-part part istate))))
  2693. (list ps
  2694. (if (< (length ps) (- end start))
  2695. (+ start (length ps))
  2696. (+ end 1000))
  2697. start end)))
  2698. (defun prepare-part (part istate)
  2699. (let ((newline '#.(string #\newline)))
  2700. (etypecase part
  2701. (string (list part))
  2702. (cons (dcase part
  2703. ((:newline) (list newline))
  2704. ((:value obj &optional str)
  2705. (list (value-part obj str (istate.parts istate))))
  2706. ((:label &rest strs)
  2707. (list (list :label (apply #'cat (mapcar #'string strs)))))
  2708. ((:action label lambda &key (refreshp t))
  2709. (list (action-part label lambda refreshp
  2710. (istate.actions istate))))
  2711. ((:line label value)
  2712. (list (princ-to-string label) ": "
  2713. (value-part value nil (istate.parts istate))
  2714. newline)))))))
  2715. (defun value-part (object string parts)
  2716. (list :value
  2717. (or string (print-part-to-string object))
  2718. (assign-index object parts)))
  2719. (defun action-part (label lambda refreshp actions)
  2720. (list :action label (assign-index (list lambda refreshp) actions)))
  2721. (defun assign-index (object vector)
  2722. (let ((index (fill-pointer vector)))
  2723. (vector-push-extend object vector)
  2724. index))
  2725. (defun print-part-to-string (value)
  2726. (let* ((*print-readably* nil)
  2727. (string (to-line value))
  2728. (pos (position value *inspector-history*)))
  2729. (if pos
  2730. (format nil "@~D=~A" pos string)
  2731. string)))
  2732. (defun content-range (list start end)
  2733. (typecase list
  2734. (list (let ((len (length list)))
  2735. (subseq list start (min len end))))
  2736. (lcons (llist-range list start end))))
  2737. (defslimefun inspector-nth-part (index)
  2738. "Return the current inspector's INDEXth part.
  2739. The second value indicates if that part exists at all."
  2740. (let* ((parts (istate.parts *istate*))
  2741. (foundp (< index (length parts))))
  2742. (values (and foundp (aref parts index))
  2743. foundp)))
  2744. (defslimefun inspect-nth-part (index)
  2745. (with-buffer-syntax ()
  2746. (inspect-object (inspector-nth-part index))))
  2747. (defslimefun inspector-range (from to)
  2748. (prepare-range *istate* from to))
  2749. (defslimefun inspector-call-nth-action (index &rest args)
  2750. (destructuring-bind (fun refreshp) (aref (istate.actions *istate*) index)
  2751. (apply fun args)
  2752. (if refreshp
  2753. (inspector-reinspect)
  2754. ;; tell emacs that we don't want to refresh the inspector buffer
  2755. nil)))
  2756. (defslimefun inspector-pop ()
  2757. "Inspect the previous object.
  2758. Return nil if there's no previous object."
  2759. (with-buffer-syntax ()
  2760. (cond ((istate.previous *istate*)
  2761. (setq *istate* (istate.previous *istate*))
  2762. (istate>elisp *istate*))
  2763. (t nil))))
  2764. (defslimefun inspector-next ()
  2765. "Inspect the next element in the history of inspected objects.."
  2766. (with-buffer-syntax ()
  2767. (cond ((istate.next *istate*)
  2768. (setq *istate* (istate.next *istate*))
  2769. (istate>elisp *istate*))
  2770. (t nil))))
  2771. (defslimefun inspector-reinspect ()
  2772. (let ((istate *istate*))
  2773. (setf (istate.content istate) (emacs-inspect/istate istate))
  2774. (istate>elisp istate)))
  2775. (defslimefun inspector-toggle-verbose ()
  2776. "Toggle verbosity of inspected object."
  2777. (setf (istate.verbose *istate*) (not (istate.verbose *istate*)))
  2778. (istate>elisp *istate*))
  2779. (defslimefun inspector-eval (string)
  2780. (let* ((obj (istate.object *istate*))
  2781. (context (eval-context obj))
  2782. (form (with-buffer-syntax ((cdr (assoc '*package* context)))
  2783. (read-from-string string)))
  2784. (ignorable (remove-if #'boundp (mapcar #'car context))))
  2785. (to-string (eval `(let ((* ',obj) (- ',form)
  2786. . ,(loop for (var . val) in context
  2787. unless (constantp var) collect
  2788. `(,var ',val)))
  2789. (declare (ignorable . ,ignorable))
  2790. ,form)))))
  2791. (defslimefun inspector-history ()
  2792. (with-output-to-string (out)
  2793. (let ((newest (loop for s = *istate* then next
  2794. for next = (istate.next s)
  2795. if (not next) return s)))
  2796. (format out "--- next/prev chain ---")
  2797. (loop for s = newest then (istate.previous s) while s do
  2798. (let ((val (istate.object s)))
  2799. (format out "~%~:[ ~; *~]@~d "
  2800. (eq s *istate*)
  2801. (position val *inspector-history*))
  2802. (print-unreadable-object (val out :type t :identity t)))))
  2803. (format out "~%~%--- all visited objects ---")
  2804. (loop for val across *inspector-history* for i from 0 do
  2805. (format out "~%~2,' d " i)
  2806. (print-unreadable-object (val out :type t :identity t)))))
  2807. (defslimefun quit-inspector ()
  2808. (reset-inspector)
  2809. nil)
  2810. (defslimefun describe-inspectee ()
  2811. "Describe the currently inspected object."
  2812. (with-buffer-syntax ()
  2813. (describe-to-string (istate.object *istate*))))
  2814. (defslimefun pprint-inspector-part (index)
  2815. "Pretty-print the currently inspected object."
  2816. (with-buffer-syntax ()
  2817. (swank-pprint (list (inspector-nth-part index)))))
  2818. (defslimefun inspect-in-frame (string index)
  2819. (with-buffer-syntax ()
  2820. (with-retry-restart (:msg "Retry SLIME inspection request.")
  2821. (reset-inspector)
  2822. (inspect-object (eval-in-frame (from-string string) index)))))
  2823. (defslimefun inspect-current-condition ()
  2824. (with-buffer-syntax ()
  2825. (reset-inspector)
  2826. (inspect-object *swank-debugger-condition*)))
  2827. (defslimefun inspect-frame-var (frame var)
  2828. (with-buffer-syntax ()
  2829. (reset-inspector)
  2830. (inspect-object (frame-var-value frame var))))
  2831. ;;;;; Lists
  2832. (defmethod emacs-inspect ((o cons))
  2833. (if (listp (cdr o))
  2834. (inspect-list o)
  2835. (inspect-cons o)))
  2836. (defun inspect-cons (cons)
  2837. (label-value-line*
  2838. ('car (car cons))
  2839. ('cdr (cdr cons))))
  2840. (defun inspect-list (list)
  2841. (multiple-value-bind (length tail) (safe-length list)
  2842. (flet ((frob (title list)
  2843. (list* title '(:newline) (inspect-list-aux list))))
  2844. (cond ((not length)
  2845. (frob "A circular list:"
  2846. (cons (car list)
  2847. (ldiff (cdr list) list))))
  2848. ((not tail)
  2849. (frob "A proper list:" list))
  2850. (t
  2851. (frob "An improper list:" list))))))
  2852. (defun inspect-list-aux (list)
  2853. (loop for i from 0 for rest on list while (consp rest) append
  2854. (if (listp (cdr rest))
  2855. (label-value-line i (car rest))
  2856. (label-value-line* (i (car rest)) (:tail (cdr rest))))))
  2857. (defun safe-length (list)
  2858. "Similar to `list-length', but avoid errors on improper lists.
  2859. Return two values: the length of the list and the last cdr.
  2860. Return NIL if LIST is circular."
  2861. (do ((n 0 (+ n 2)) ;Counter.
  2862. (fast list (cddr fast)) ;Fast pointer: leaps by 2.
  2863. (slow list (cdr slow))) ;Slow pointer: leaps by 1.
  2864. (nil)
  2865. (cond ((null fast) (return (values n nil)))
  2866. ((not (consp fast)) (return (values n fast)))
  2867. ((null (cdr fast)) (return (values (1+ n) (cdr fast))))
  2868. ((and (eq fast slow) (> n 0)) (return nil))
  2869. ((not (consp (cdr fast))) (return (values (1+ n) (cdr fast)))))))
  2870. ;;;;; Hashtables
  2871. (defun hash-table-to-alist (ht)
  2872. (let ((result '()))
  2873. (maphash (lambda (key value)
  2874. (setq result (acons key value result)))
  2875. ht)
  2876. result))
  2877. (defmethod emacs-inspect ((ht hash-table))
  2878. (append
  2879. (label-value-line*
  2880. ("Count" (hash-table-count ht))
  2881. ("Size" (hash-table-size ht))
  2882. ("Test" (hash-table-test ht))
  2883. ("Rehash size" (hash-table-rehash-size ht))
  2884. ("Rehash threshold" (hash-table-rehash-threshold ht)))
  2885. (let ((weakness (hash-table-weakness ht)))
  2886. (when weakness
  2887. (label-value-line "Weakness:" weakness)))
  2888. (unless (zerop (hash-table-count ht))
  2889. `((:action "[clear hashtable]"
  2890. ,(lambda () (clrhash ht))) (:newline)
  2891. "Contents: " (:newline)))
  2892. (let ((content (hash-table-to-alist ht)))
  2893. (cond ((every (lambda (x) (typep (first x) '(or string symbol))) content)
  2894. (setf content (sort content 'string< :key #'first)))
  2895. ((every (lambda (x) (typep (first x) 'real)) content)
  2896. (setf content (sort content '< :key #'first))))
  2897. (loop for (key . value) in content appending
  2898. `((:value ,key) " = " (:value ,value)
  2899. " " (:action "[remove entry]"
  2900. ,(let ((key key))
  2901. (lambda () (remhash key ht))))
  2902. (:newline))))))
  2903. ;;;;; Arrays
  2904. (defmethod emacs-inspect ((array array))
  2905. (lcons*
  2906. (iline "Dimensions" (array-dimensions array))
  2907. (iline "Element type" (array-element-type array))
  2908. (iline "Total size" (array-total-size array))
  2909. (iline "Adjustable" (adjustable-array-p array))
  2910. (iline "Fill pointer" (if (array-has-fill-pointer-p array)
  2911. (fill-pointer array)))
  2912. "Contents:" '(:newline)
  2913. (labels ((k (i max)
  2914. (cond ((= i max) '())
  2915. (t (lcons (iline i (row-major-aref array i))
  2916. (k (1+ i) max))))))
  2917. (k 0 (array-total-size array)))))
  2918. ;;;;; Chars
  2919. (defmethod emacs-inspect ((char character))
  2920. (append
  2921. (label-value-line*
  2922. ("Char code" (char-code char))
  2923. ("Lower cased" (char-downcase char))
  2924. ("Upper cased" (char-upcase char)))
  2925. (if (get-macro-character char)
  2926. `("In the current readtable ("
  2927. (:value ,*readtable*) ") it is a macro character: "
  2928. (:value ,(get-macro-character char))))))
  2929. ;;;; Thread listing
  2930. (defvar *thread-list* ()
  2931. "List of threads displayed in Emacs. We don't care a about
  2932. synchronization issues (yet). There can only be one thread listing at
  2933. a time.")
  2934. (defslimefun list-threads ()
  2935. "Return a list (LABELS (ID NAME STATUS ATTRS ...) ...).
  2936. LABELS is a list of attribute names and the remaining lists are the
  2937. corresponding attribute values per thread.
  2938. Example:
  2939. ((:id :name :status :priority)
  2940. (6 \"swank-indentation-cache-thread\" \"Semaphore timed wait\" 0)
  2941. (5 \"reader-thread\" \"Active\" 0)
  2942. (4 \"control-thread\" \"Semaphore timed wait\" 0)
  2943. (2 \"Swank Sentinel\" \"Semaphore timed wait\" 0)
  2944. (1 \"listener\" \"Active\" 0)
  2945. (0 \"Initial\" \"Sleep\" 0))"
  2946. (setq *thread-list* (all-threads))
  2947. (when (and *emacs-connection*
  2948. (use-threads-p)
  2949. (equalp (thread-name (current-thread)) "worker"))
  2950. (setf *thread-list* (delete (current-thread) *thread-list*)))
  2951. (let* ((plist (thread-attributes (car *thread-list*)))
  2952. (labels (loop for (key) on plist by #'cddr
  2953. collect key)))
  2954. `((:id :name :status ,@labels)
  2955. ,@(loop for thread in *thread-list*
  2956. for name = (thread-name thread)
  2957. for attributes = (thread-attributes thread)
  2958. collect (list* (thread-id thread)
  2959. (string name)
  2960. (thread-status thread)
  2961. (loop for label in labels
  2962. collect (getf attributes label)))))))
  2963. (defslimefun quit-thread-browser ()
  2964. (setq *thread-list* nil))
  2965. (defun nth-thread (index)
  2966. (nth index *thread-list*))
  2967. (defslimefun debug-nth-thread (index)
  2968. (let ((connection *emacs-connection*))
  2969. (queue-thread-interrupt
  2970. (nth-thread index)
  2971. (lambda ()
  2972. (with-connection (connection)
  2973. (simple-break))))))
  2974. (defslimefun kill-nth-thread (index)
  2975. (kill-thread (nth-thread index)))
  2976. (defslimefun start-swank-server-in-thread (index port-file-name)
  2977. "Interrupt the INDEXth thread and make it start a swank server.
  2978. The server port is written to PORT-FILE-NAME."
  2979. (interrupt-thread (nth-thread index)
  2980. (lambda ()
  2981. (start-server port-file-name :style nil))))
  2982. ;;;; Class browser
  2983. (defun mop-helper (class-name fn)
  2984. (let ((class (find-class class-name nil)))
  2985. (if class
  2986. (mapcar (lambda (x) (to-string (class-name x)))
  2987. (funcall fn class)))))
  2988. (defslimefun mop (type symbol-name)
  2989. "Return info about classes using mop.
  2990. When type is:
  2991. :subclasses - return the list of subclasses of class.
  2992. :superclasses - return the list of superclasses of class."
  2993. (let ((symbol (parse-symbol symbol-name *buffer-package*)))
  2994. (ecase type
  2995. (:subclasses
  2996. (mop-helper symbol #'swank-mop:class-direct-subclasses))
  2997. (:superclasses
  2998. (mop-helper symbol #'swank-mop:class-direct-superclasses)))))
  2999. ;;;; Automatically synchronized state
  3000. ;;;
  3001. ;;; Here we add hooks to push updates of relevant information to
  3002. ;;; Emacs.
  3003. ;;;;; *FEATURES*
  3004. (defun sync-features-to-emacs ()
  3005. "Update Emacs if any relevant Lisp state has changed."
  3006. ;; FIXME: *slime-features* should be connection-local
  3007. (unless (eq *slime-features* *features*)
  3008. (setq *slime-features* *features*)
  3009. (send-to-emacs (list :new-features (features-for-emacs)))))
  3010. (defun features-for-emacs ()
  3011. "Return `*slime-features*' in a format suitable to send it to Emacs."
  3012. *slime-features*)
  3013. (add-hook *pre-reply-hook* 'sync-features-to-emacs)
  3014. ;;;;; Indentation of macros
  3015. ;;;
  3016. ;;; This code decides how macros should be indented (based on their
  3017. ;;; arglists) and tells Emacs. A per-connection cache is used to avoid
  3018. ;;; sending redundant information to Emacs -- we just say what's
  3019. ;;; changed since last time.
  3020. ;;;
  3021. ;;; The strategy is to scan all symbols, pick out the macros, and look
  3022. ;;; for &body-arguments.
  3023. (defvar *configure-emacs-indentation* t
  3024. "When true, automatically send indentation information to Emacs
  3025. after each command.")
  3026. (defslimefun update-indentation-information ()
  3027. (send-to-indentation-cache `(:update-indentation-information))
  3028. nil)
  3029. ;; This function is for *PRE-REPLY-HOOK*.
  3030. (defun sync-indentation-to-emacs ()
  3031. "Send any indentation updates to Emacs via CONNECTION."
  3032. (when *configure-emacs-indentation*
  3033. (send-to-indentation-cache `(:sync-indentation ,*buffer-package*))))
  3034. ;; Send REQUEST to the cache. If we are single threaded perform the
  3035. ;; request right away, otherwise delegate the request to the
  3036. ;; indentation-cache-thread.
  3037. (defun send-to-indentation-cache (request)
  3038. (let ((c *emacs-connection*))
  3039. (etypecase c
  3040. (singlethreaded-connection
  3041. (handle-indentation-cache-request c request))
  3042. (multithreaded-connection
  3043. (without-slime-interrupts
  3044. (send (mconn.indentation-cache-thread c) request))))))
  3045. (defun indentation-cache-loop (connection)
  3046. (with-connection (connection)
  3047. (loop
  3048. (restart-case
  3049. (handle-indentation-cache-request connection (receive))
  3050. (abort ()
  3051. :report "Return to the indentation cache request handling loop.")))))
  3052. (defun handle-indentation-cache-request (connection request)
  3053. (dcase request
  3054. ((:sync-indentation package)
  3055. (let ((fullp (need-full-indentation-update-p connection)))
  3056. (perform-indentation-update connection fullp package)))
  3057. ((:update-indentation-information)
  3058. (perform-indentation-update connection t nil))))
  3059. (defun need-full-indentation-update-p (connection)
  3060. "Return true if the whole indentation cache should be updated.
  3061. This is a heuristic to avoid scanning all symbols all the time:
  3062. instead, we only do a full scan if the set of packages has changed."
  3063. (set-difference (list-all-packages)
  3064. (connection.indentation-cache-packages connection)))
  3065. (defun perform-indentation-update (connection force package)
  3066. "Update the indentation cache in CONNECTION and update Emacs.
  3067. If FORCE is true then start again without considering the old cache."
  3068. (let ((cache (connection.indentation-cache connection)))
  3069. (when force (clrhash cache))
  3070. (let ((delta (update-indentation/delta-for-emacs cache force package)))
  3071. (setf (connection.indentation-cache-packages connection)
  3072. (list-all-packages))
  3073. (unless (null delta)
  3074. (setf (connection.indentation-cache connection) cache)
  3075. (send-to-emacs (list :indentation-update delta))))))
  3076. (defun update-indentation/delta-for-emacs (cache force package)
  3077. "Update the cache and return the changes in a (SYMBOL INDENT PACKAGES) list.
  3078. If FORCE is true then check all symbols, otherwise only check symbols
  3079. belonging to PACKAGE."
  3080. (let ((alist '()))
  3081. (flet ((consider (symbol)
  3082. (let ((indent (symbol-indentation symbol)))
  3083. (when indent
  3084. (unless (equal (gethash symbol cache) indent)
  3085. (setf (gethash symbol cache) indent)
  3086. (let ((pkgs (mapcar #'package-name
  3087. (symbol-packages symbol)))
  3088. (name (string-downcase symbol)))
  3089. (push (list name indent pkgs) alist)))))))
  3090. (cond (force
  3091. (do-all-symbols (symbol)
  3092. (consider symbol)))
  3093. ((package-name package) ; don't try to iterate over a
  3094. ; deleted package.
  3095. (do-symbols (symbol package)
  3096. (when (eq (symbol-package symbol) package)
  3097. (consider symbol)))))
  3098. alist)))
  3099. (defun package-names (package)
  3100. "Return the name and all nicknames of PACKAGE in a fresh list."
  3101. (cons (package-name package) (copy-list (package-nicknames package))))
  3102. (defun symbol-packages (symbol)
  3103. "Return the packages where SYMBOL can be found."
  3104. (let ((string (string symbol)))
  3105. (loop for p in (list-all-packages)
  3106. when (eq symbol (find-symbol string p))
  3107. collect p)))
  3108. (defun cl-symbol-p (symbol)
  3109. "Is SYMBOL a symbol in the COMMON-LISP package?"
  3110. (eq (symbol-package symbol) cl-package))
  3111. (defun known-to-emacs-p (symbol)
  3112. "Return true if Emacs has special rules for indenting SYMBOL."
  3113. (cl-symbol-p symbol))
  3114. (defun symbol-indentation (symbol)
  3115. "Return a form describing the indentation of SYMBOL.
  3116. The form is to be used as the `common-lisp-indent-function' property
  3117. in Emacs."
  3118. (if (and (macro-function symbol)
  3119. (not (known-to-emacs-p symbol)))
  3120. (let ((arglist (arglist symbol)))
  3121. (etypecase arglist
  3122. ((member :not-available)
  3123. nil)
  3124. (list
  3125. (macro-indentation arglist))))
  3126. nil))
  3127. (defun macro-indentation (arglist)
  3128. (if (well-formed-list-p arglist)
  3129. (position '&body (remove '&optional (clean-arglist arglist)))
  3130. nil))
  3131. (defun clean-arglist (arglist)
  3132. "Remove &whole, &enviroment, and &aux elements from ARGLIST."
  3133. (cond ((null arglist) '())
  3134. ((member (car arglist) '(&whole &environment))
  3135. (clean-arglist (cddr arglist)))
  3136. ((eq (car arglist) '&aux)
  3137. '())
  3138. (t (cons (car arglist) (clean-arglist (cdr arglist))))))
  3139. (defun well-formed-list-p (list)
  3140. "Is LIST a proper list terminated by NIL?"
  3141. (typecase list
  3142. (null t)
  3143. (cons (well-formed-list-p (cdr list)))
  3144. (t nil)))
  3145. (defun print-indentation-lossage (&optional (stream *standard-output*))
  3146. "Return the list of symbols whose indentation styles collide incompatibly.
  3147. Collisions are caused because package information is ignored."
  3148. (let ((table (make-hash-table :test 'equal)))
  3149. (flet ((name (s) (string-downcase (symbol-name s))))
  3150. (do-all-symbols (s)
  3151. (setf (gethash (name s) table)
  3152. (cons s (symbol-indentation s))))
  3153. (let ((collisions '()))
  3154. (do-all-symbols (s)
  3155. (let* ((entry (gethash (name s) table))
  3156. (owner (car entry))
  3157. (indent (cdr entry)))
  3158. (unless (or (eq s owner)
  3159. (equal (symbol-indentation s) indent)
  3160. (and (not (fboundp s))
  3161. (null (macro-function s))))
  3162. (pushnew owner collisions)
  3163. (pushnew s collisions))))
  3164. (if (null collisions)
  3165. (format stream "~&No worries!~%")
  3166. (format stream "~&Symbols with collisions:~%~{ ~S~%~}"
  3167. collisions))))))
  3168. ;;; FIXME: it's too slow on CLASP right now, remove once it's fast enough.
  3169. #-clasp
  3170. (add-hook *pre-reply-hook* 'sync-indentation-to-emacs)
  3171. (defun make-output-function-for-target (connection target)
  3172. "Create a function to send user output to a specific TARGET in Emacs."
  3173. (lambda (string)
  3174. (swank::with-connection (connection)
  3175. (with-simple-restart
  3176. (abort "Abort sending output to Emacs.")
  3177. (swank::send-to-emacs `(:write-string ,string ,target))))))
  3178. (defun make-output-stream-for-target (connection target)
  3179. "Create a stream that sends output to a specific TARGET in Emacs."
  3180. (make-output-stream (make-output-function-for-target connection target)))
  3181. ;;;; Testing
  3182. (defslimefun io-speed-test (&optional (n 1000) (m 1))
  3183. (let* ((s *standard-output*)
  3184. (*trace-output* (make-broadcast-stream s *log-output*)))
  3185. (time (progn
  3186. (dotimes (i n)
  3187. (format s "~D abcdefghijklm~%" i)
  3188. (when (zerop (mod n m))
  3189. (finish-output s)))
  3190. (finish-output s)
  3191. (when *emacs-connection*
  3192. (eval-in-emacs '(message "done.")))))
  3193. (terpri *trace-output*)
  3194. (finish-output *trace-output*)
  3195. nil))
  3196. (defslimefun flow-control-test (n delay)
  3197. (let ((stream (make-output-stream
  3198. (let ((conn *emacs-connection*))
  3199. (lambda (string)
  3200. (declare (ignore string))
  3201. (with-connection (conn)
  3202. (send-to-emacs `(:test-delay ,delay))))))))
  3203. (dotimes (i n)
  3204. (print i stream)
  3205. (force-output stream)
  3206. (background-message "flow-control-test: ~d" i))))
  3207. (defun before-init (version load-path)
  3208. (pushnew :swank *features*)
  3209. (setq *swank-wire-protocol-version* version)
  3210. (setq *load-path* load-path))
  3211. (defun init ()
  3212. (run-hook *after-init-hook*))
  3213. ;; Local Variables:
  3214. ;; coding: latin-1-unix
  3215. ;; indent-tabs-mode: nil
  3216. ;; outline-regexp: ";;;;;*"
  3217. ;; End:
  3218. ;;; swank.lisp ends here