Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1579 lines
56 KiB

4 years ago
  1. ;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;;*" -*-
  2. ;;;
  3. ;;; slime-backend.lisp --- SLIME backend interface.
  4. ;;;
  5. ;;; Created by James Bielman in 2003. Released into the public domain.
  6. ;;;
  7. ;;;; Frontmatter
  8. ;;;
  9. ;;; This file defines the functions that must be implemented
  10. ;;; separately for each Lisp. Each is declared as a generic function
  11. ;;; for which swank-<implementation>.lisp provides methods.
  12. (in-package swank/backend)
  13. ;;;; Metacode
  14. (defparameter *debug-swank-backend* nil
  15. "If this is true, backends should not catch errors but enter the
  16. debugger where appropriate. Also, they should not perform backtrace
  17. magic but really show every frame including SWANK related ones.")
  18. (defparameter *interface-functions* '()
  19. "The names of all interface functions.")
  20. (defparameter *unimplemented-interfaces* '()
  21. "List of interface functions that are not implemented.
  22. DEFINTERFACE adds to this list and DEFIMPLEMENTATION removes.")
  23. (defvar *log-output* nil) ; should be nil for image dumpers
  24. (defmacro definterface (name args documentation &rest default-body)
  25. "Define an interface function for the backend to implement.
  26. A function is defined with NAME, ARGS, and DOCUMENTATION. This
  27. function first looks for a function to call in NAME's property list
  28. that is indicated by 'IMPLEMENTATION; failing that, it looks for a
  29. function indicated by 'DEFAULT. If neither is present, an error is
  30. signaled.
  31. If a DEFAULT-BODY is supplied, then a function with the same body and
  32. ARGS will be added to NAME's property list as the property indicated
  33. by 'DEFAULT.
  34. Backends implement these functions using DEFIMPLEMENTATION."
  35. (check-type documentation string "a documentation string")
  36. (assert (every #'symbolp args) ()
  37. "Complex lambda-list not supported: ~S ~S" name args)
  38. (labels ((gen-default-impl ()
  39. `(setf (get ',name 'default) (lambda ,args ,@default-body)))
  40. (args-as-list (args)
  41. (destructuring-bind (req opt key rest) (parse-lambda-list args)
  42. `(,@req ,@opt
  43. ,@(loop for k in key append `(,(kw k) ,k))
  44. ,@(or rest '(())))))
  45. (parse-lambda-list (args)
  46. (parse args '(&optional &key &rest)
  47. (make-array 4 :initial-element nil)))
  48. (parse (args keywords vars)
  49. (cond ((null args)
  50. (reverse (map 'list #'reverse vars)))
  51. ((member (car args) keywords)
  52. (parse (cdr args) (cdr (member (car args) keywords)) vars))
  53. (t (push (car args) (aref vars (length keywords)))
  54. (parse (cdr args) keywords vars))))
  55. (kw (s) (intern (string s) :keyword)))
  56. `(progn
  57. (defun ,name ,args
  58. ,documentation
  59. (let ((f (or (get ',name 'implementation)
  60. (get ',name 'default))))
  61. (cond (f (apply f ,@(args-as-list args)))
  62. (t (error "~S not implemented" ',name)))))
  63. (pushnew ',name *interface-functions*)
  64. ,(if (null default-body)
  65. `(pushnew ',name *unimplemented-interfaces*)
  66. (gen-default-impl))
  67. (eval-when (:compile-toplevel :load-toplevel :execute)
  68. (export ',name :swank/backend))
  69. ',name)))
  70. (defmacro defimplementation (name args &body body)
  71. (assert (every #'symbolp args) ()
  72. "Complex lambda-list not supported: ~S ~S" name args)
  73. `(progn
  74. (setf (get ',name 'implementation)
  75. ;; For implicit BLOCK. FLET because of interplay w/ decls.
  76. (flet ((,name ,args ,@body)) #',name))
  77. (if (member ',name *interface-functions*)
  78. (setq *unimplemented-interfaces*
  79. (remove ',name *unimplemented-interfaces*))
  80. (warn "DEFIMPLEMENTATION of undefined interface (~S)" ',name))
  81. ',name))
  82. (defun warn-unimplemented-interfaces ()
  83. "Warn the user about unimplemented backend features.
  84. The portable code calls this function at startup."
  85. (let ((*print-pretty* t))
  86. (warn "These Swank interfaces are unimplemented:~% ~:<~{~A~^ ~:_~}~:>"
  87. (list (sort (copy-list *unimplemented-interfaces*) #'string<)))))
  88. (defun import-to-swank-mop (symbol-list)
  89. (dolist (sym symbol-list)
  90. (let* ((swank-mop-sym (find-symbol (symbol-name sym) :swank-mop)))
  91. (when swank-mop-sym
  92. (unintern swank-mop-sym :swank-mop))
  93. (import sym :swank-mop)
  94. (export sym :swank-mop))))
  95. (defun import-swank-mop-symbols (package except)
  96. "Import the mop symbols from PACKAGE to SWANK-MOP.
  97. EXCEPT is a list of symbol names which should be ignored."
  98. (do-symbols (s :swank-mop)
  99. (unless (member s except :test #'string=)
  100. (let ((real-symbol (find-symbol (string s) package)))
  101. (assert real-symbol () "Symbol ~A not found in package ~A" s package)
  102. (unintern s :swank-mop)
  103. (import real-symbol :swank-mop)
  104. (export real-symbol :swank-mop)))))
  105. (definterface gray-package-name ()
  106. "Return a package-name that contains the Gray stream symbols.
  107. This will be used like so:
  108. (defpackage foo
  109. (:import-from #.(gray-package-name) . #.*gray-stream-symbols*)")
  110. ;;;; Utilities
  111. (defmacro with-struct ((conc-name &rest names) obj &body body)
  112. "Like with-slots but works only for structs."
  113. (check-type conc-name symbol)
  114. (flet ((reader (slot)
  115. (intern (concatenate 'string
  116. (symbol-name conc-name)
  117. (symbol-name slot))
  118. (symbol-package conc-name))))
  119. (let ((tmp (gensym "OO-")))
  120. ` (let ((,tmp ,obj))
  121. (symbol-macrolet
  122. ,(loop for name in names collect
  123. (typecase name
  124. (symbol `(,name (,(reader name) ,tmp)))
  125. (cons `(,(first name) (,(reader (second name)) ,tmp)))
  126. (t (error "Malformed syntax in WITH-STRUCT: ~A" name))))
  127. ,@body)))))
  128. (defmacro when-let ((var value) &body body)
  129. `(let ((,var ,value))
  130. (when ,var ,@body)))
  131. (defun boolean-to-feature-expression (value)
  132. "Converts a boolean VALUE to a form suitable for testing with #+."
  133. (if value
  134. '(:and)
  135. '(:or)))
  136. (defun with-symbol (name package)
  137. "Check if a symbol with a given NAME exists in PACKAGE and returns a
  138. form suitable for testing with #+."
  139. (boolean-to-feature-expression
  140. (and (find-package package)
  141. (find-symbol (string name) package))))
  142. (defun choose-symbol (package name alt-package alt-name)
  143. "If symbol package:name exists return that symbol, otherwise alt-package:alt-name.
  144. Suitable for use with #."
  145. (or (and (find-package package)
  146. (find-symbol (string name) package))
  147. (find-symbol (string alt-name) alt-package)))
  148. ;;;; UFT8
  149. (deftype octet () '(unsigned-byte 8))
  150. (deftype octets () '(simple-array octet (*)))
  151. ;; Helper function. Decode the next N bytes starting from INDEX.
  152. ;; Return the decoded char and the new index.
  153. (defun utf8-decode-aux (buffer index limit byte0 n)
  154. (declare (type octets buffer) (fixnum index limit byte0 n))
  155. (if (< (- limit index) n)
  156. (values nil index)
  157. (do ((i 0 (1+ i))
  158. (code byte0 (let ((byte (aref buffer (+ index i))))
  159. (cond ((= (ldb (byte 2 6) byte) #b10)
  160. (+ (ash code 6) (ldb (byte 6 0) byte)))
  161. (t
  162. (error "Invalid encoding"))))))
  163. ((= i n)
  164. (values (cond ((<= code #xff) (code-char code))
  165. ((<= #xd800 code #xdfff)
  166. (error "Invalid Unicode code point: #x~x" code))
  167. ((and (< code char-code-limit)
  168. (code-char code)))
  169. (t
  170. (error
  171. "Can't represent code point: #x~x ~
  172. (char-code-limit is #x~x)"
  173. code char-code-limit)))
  174. (+ index n))))))
  175. ;; Decode one character in BUFFER starting at INDEX.
  176. ;; Return 2 values: the character and the new index.
  177. ;; If there aren't enough bytes between INDEX and LIMIT return nil.
  178. (defun utf8-decode (buffer index limit)
  179. (declare (type octets buffer) (fixnum index limit))
  180. (if (= index limit)
  181. (values nil index)
  182. (let ((b (aref buffer index)))
  183. (if (<= b #x7f)
  184. (values (code-char b) (1+ index))
  185. (macrolet ((try (marker else)
  186. (let* ((l (integer-length marker))
  187. (n (- l 2)))
  188. `(if (= (ldb (byte ,l ,(- 8 l)) b) ,marker)
  189. (utf8-decode-aux buffer (1+ index) limit
  190. (ldb (byte ,(- 8 l) 0) b)
  191. ,n)
  192. ,else))))
  193. (try #b110
  194. (try #b1110
  195. (try #b11110
  196. (try #b111110
  197. (try #b1111110
  198. (error "Invalid encoding")))))))))))
  199. ;; Decode characters from BUFFER and write them to STRING.
  200. ;; Return 2 values: LASTINDEX and LASTSTART where
  201. ;; LASTINDEX is the last index in BUFFER that was not decoded
  202. ;; and LASTSTART is the last index in STRING not written.
  203. (defun utf8-decode-into (buffer index limit string start end)
  204. (declare (string string) (fixnum index limit start end) (type octets buffer))
  205. (loop
  206. (cond ((= start end)
  207. (return (values index start)))
  208. (t
  209. (multiple-value-bind (c i) (utf8-decode buffer index limit)
  210. (cond (c
  211. (setf (aref string start) c)
  212. (setq index i)
  213. (setq start (1+ start)))
  214. (t
  215. (return (values index start)))))))))
  216. (defun default-utf8-to-string (octets)
  217. (let* ((limit (length octets))
  218. (str (make-string limit)))
  219. (multiple-value-bind (i s) (utf8-decode-into octets 0 limit str 0 limit)
  220. (if (= i limit)
  221. (if (= limit s)
  222. str
  223. (adjust-array str s))
  224. (loop
  225. (let ((end (+ (length str) (- limit i))))
  226. (setq str (adjust-array str end))
  227. (multiple-value-bind (i2 s2)
  228. (utf8-decode-into octets i limit str s end)
  229. (cond ((= i2 limit)
  230. (return (adjust-array str s2)))
  231. (t
  232. (setq i i2)
  233. (setq s s2))))))))))
  234. (defmacro utf8-encode-aux (code buffer start end n)
  235. `(cond ((< (- ,end ,start) ,n)
  236. ,start)
  237. (t
  238. (setf (aref ,buffer ,start)
  239. (dpb (ldb (byte ,(- 7 n) ,(* 6 (1- n))) ,code)
  240. (byte ,(- 7 n) 0)
  241. ,(dpb 0 (byte 1 (- 7 n)) #xff)))
  242. ,@(loop for i from 0 upto (- n 2) collect
  243. `(setf (aref ,buffer (+ ,start ,(- n 1 i)))
  244. (dpb (ldb (byte 6 ,(* 6 i)) ,code)
  245. (byte 6 0)
  246. #b10111111)))
  247. (+ ,start ,n))))
  248. (defun %utf8-encode (code buffer start end)
  249. (declare (type (unsigned-byte 31) code) (type octets buffer)
  250. (type (and fixnum unsigned-byte) start end))
  251. (cond ((<= code #x7f)
  252. (cond ((< start end)
  253. (setf (aref buffer start) code)
  254. (1+ start))
  255. (t start)))
  256. ((<= code #x7ff) (utf8-encode-aux code buffer start end 2))
  257. ((<= #xd800 code #xdfff)
  258. (error "Invalid Unicode code point (surrogate): #x~x" code))
  259. ((<= code #xffff) (utf8-encode-aux code buffer start end 3))
  260. ((<= code #x1fffff) (utf8-encode-aux code buffer start end 4))
  261. ((<= code #x3ffffff) (utf8-encode-aux code buffer start end 5))
  262. (t (utf8-encode-aux code buffer start end 6))))
  263. (defun utf8-encode (char buffer start end)
  264. (declare (type character char) (type octets buffer)
  265. (type (and fixnum unsigned-byte) start end))
  266. (%utf8-encode (char-code char) buffer start end))
  267. (defun utf8-encode-into (string start end buffer index limit)
  268. (declare (string string) (type octets buffer) (fixnum start end index limit))
  269. (loop
  270. (cond ((= start end)
  271. (return (values start index)))
  272. ((= index limit)
  273. (return (values start index)))
  274. (t
  275. (let ((i2 (utf8-encode (char string start) buffer index limit)))
  276. (cond ((= i2 index)
  277. (return (values start index)))
  278. (t
  279. (setq index i2)
  280. (incf start))))))))
  281. (defun default-string-to-utf8 (string)
  282. (let* ((len (length string))
  283. (b (make-array len :element-type 'octet)))
  284. (multiple-value-bind (s i) (utf8-encode-into string 0 len b 0 len)
  285. (if (= s len)
  286. b
  287. (loop
  288. (let ((limit (+ (length b) (- len s))))
  289. (setq b (coerce (adjust-array b limit) 'octets))
  290. (multiple-value-bind (s2 i2)
  291. (utf8-encode-into string s len b i limit)
  292. (cond ((= s2 len)
  293. (return (coerce (adjust-array b i2) 'octets)))
  294. (t
  295. (setq i i2)
  296. (setq s s2))))))))))
  297. (definterface string-to-utf8 (string)
  298. "Convert the string STRING to a (simple-array (unsigned-byte 8))"
  299. (default-string-to-utf8 string))
  300. (definterface utf8-to-string (octets)
  301. "Convert the (simple-array (unsigned-byte 8)) OCTETS to a string."
  302. (default-utf8-to-string octets))
  303. ;;;; TCP server
  304. (definterface create-socket (host port &key backlog)
  305. "Create a listening TCP socket on interface HOST and port PORT.
  306. BACKLOG queue length for incoming connections.")
  307. (definterface local-port (socket)
  308. "Return the local port number of SOCKET.")
  309. (definterface close-socket (socket)
  310. "Close the socket SOCKET.")
  311. (definterface accept-connection (socket &key external-format
  312. buffering timeout)
  313. "Accept a client connection on the listening socket SOCKET.
  314. Return a stream for the new connection.
  315. If EXTERNAL-FORMAT is nil return a binary stream
  316. otherwise create a character stream.
  317. BUFFERING can be one of:
  318. nil ... no buffering
  319. t ... enable buffering
  320. :line ... enable buffering with automatic flushing on eol.")
  321. (definterface add-sigio-handler (socket fn)
  322. "Call FN whenever SOCKET is readable.")
  323. (definterface remove-sigio-handlers (socket)
  324. "Remove all sigio handlers for SOCKET.")
  325. (definterface add-fd-handler (socket fn)
  326. "Call FN when Lisp is waiting for input and SOCKET is readable.")
  327. (definterface remove-fd-handlers (socket)
  328. "Remove all fd-handlers for SOCKET.")
  329. (definterface preferred-communication-style ()
  330. "Return one of the symbols :spawn, :sigio, :fd-handler, or NIL."
  331. nil)
  332. (definterface set-stream-timeout (stream timeout)
  333. "Set the 'stream 'timeout. The timeout is either the real number
  334. specifying the timeout in seconds or 'nil for no timeout."
  335. (declare (ignore stream timeout))
  336. nil)
  337. ;;; Base condition for networking errors.
  338. (define-condition network-error (simple-error) ())
  339. (definterface emacs-connected ()
  340. "Hook called when the first connection from Emacs is established.
  341. Called from the INIT-FN of the socket server that accepts the
  342. connection.
  343. This is intended for setting up extra context, e.g. to discover
  344. that the calling thread is the one that interacts with Emacs."
  345. nil)
  346. ;;;; Unix signals
  347. (defconstant +sigint+ 2)
  348. (definterface getpid ()
  349. "Return the (Unix) process ID of this superior Lisp.")
  350. (definterface install-sigint-handler (function)
  351. "Call FUNCTION on SIGINT (instead of invoking the debugger).
  352. Return old signal handler."
  353. (declare (ignore function))
  354. nil)
  355. (definterface call-with-user-break-handler (handler function)
  356. "Install the break handler HANDLER while executing FUNCTION."
  357. (let ((old-handler (install-sigint-handler handler)))
  358. (unwind-protect (funcall function)
  359. (install-sigint-handler old-handler))))
  360. (definterface quit-lisp ()
  361. "Exit the current lisp image.")
  362. (definterface lisp-implementation-type-name ()
  363. "Return a short name for the Lisp implementation."
  364. (lisp-implementation-type))
  365. (definterface lisp-implementation-program ()
  366. "Return the argv[0] of the running Lisp process, or NIL."
  367. (let ((file (car (command-line-args))))
  368. (when (and file (probe-file file))
  369. (namestring (truename file)))))
  370. (definterface socket-fd (socket-stream)
  371. "Return the file descriptor for SOCKET-STREAM.")
  372. (definterface make-fd-stream (fd external-format)
  373. "Create a character stream for the file descriptor FD.")
  374. (definterface dup (fd)
  375. "Duplicate a file descriptor.
  376. If the syscall fails, signal a condition.
  377. See dup(2).")
  378. (definterface exec-image (image-file args)
  379. "Replace the current process with a new process image.
  380. The new image is created by loading the previously dumped
  381. core file IMAGE-FILE.
  382. ARGS is a list of strings passed as arguments to
  383. the new image.
  384. This is thin wrapper around exec(3).")
  385. (definterface command-line-args ()
  386. "Return a list of strings as passed by the OS."
  387. nil)
  388. ;; pathnames are sooo useless
  389. (definterface filename-to-pathname (filename)
  390. "Return a pathname for FILENAME.
  391. A filename in Emacs may for example contain asterisks which should not
  392. be translated to wildcards."
  393. (parse-namestring filename))
  394. (definterface pathname-to-filename (pathname)
  395. "Return the filename for PATHNAME."
  396. (namestring pathname))
  397. (definterface default-directory ()
  398. "Return the default directory."
  399. (directory-namestring (truename *default-pathname-defaults*)))
  400. (definterface set-default-directory (directory)
  401. "Set the default directory.
  402. This is used to resolve filenames without directory component."
  403. (setf *default-pathname-defaults* (truename (merge-pathnames directory)))
  404. (default-directory))
  405. (definterface call-with-syntax-hooks (fn)
  406. "Call FN with hooks to handle special syntax."
  407. (funcall fn))
  408. (definterface default-readtable-alist ()
  409. "Return a suitable initial value for SWANK:*READTABLE-ALIST*."
  410. '())
  411. ;;;; Packages
  412. (definterface package-local-nicknames (package)
  413. "Returns an alist of (local-nickname . actual-package) describing the
  414. nicknames local to the designated package."
  415. (declare (ignore package))
  416. nil)
  417. (definterface find-locally-nicknamed-package (name base-package)
  418. "Return the package whose local nickname in BASE-PACKAGE matches NAME.
  419. Return NIL if local nicknames are not implemented or if there is no
  420. such package."
  421. (cdr (assoc name (package-local-nicknames base-package) :test #'string-equal)))
  422. ;;;; Compilation
  423. (definterface call-with-compilation-hooks (func)
  424. "Call FUNC with hooks to record compiler conditions.")
  425. (defmacro with-compilation-hooks ((&rest ignore) &body body)
  426. "Execute BODY as in CALL-WITH-COMPILATION-HOOKS."
  427. (declare (ignore ignore))
  428. `(call-with-compilation-hooks (lambda () (progn ,@body))))
  429. (definterface swank-compile-string (string &key buffer position filename
  430. policy)
  431. "Compile source from STRING.
  432. During compilation, compiler conditions must be trapped and
  433. resignalled as COMPILER-CONDITIONs.
  434. If supplied, BUFFER and POSITION specify the source location in Emacs.
  435. Additionally, if POSITION is supplied, it must be added to source
  436. positions reported in compiler conditions.
  437. If FILENAME is specified it may be used by certain implementations to
  438. rebind *DEFAULT-PATHNAME-DEFAULTS* which may improve the recording of
  439. source information.
  440. If POLICY is supplied, and non-NIL, it may be used by certain
  441. implementations to compile with optimization qualities of its
  442. value.
  443. Should return T on successful compilation, NIL otherwise.
  444. ")
  445. (definterface swank-compile-file (input-file output-file load-p
  446. external-format
  447. &key policy)
  448. "Compile INPUT-FILE signalling COMPILE-CONDITIONs.
  449. If LOAD-P is true, load the file after compilation.
  450. EXTERNAL-FORMAT is a value returned by find-external-format or
  451. :default.
  452. If POLICY is supplied, and non-NIL, it may be used by certain
  453. implementations to compile with optimization qualities of its
  454. value.
  455. Should return OUTPUT-TRUENAME, WARNINGS-P and FAILURE-p
  456. like `compile-file'")
  457. (deftype severity ()
  458. '(member :error :read-error :warning :style-warning :note :redefinition))
  459. ;; Base condition type for compiler errors, warnings and notes.
  460. (define-condition compiler-condition (condition)
  461. ((original-condition
  462. ;; The original condition thrown by the compiler if appropriate.
  463. ;; May be NIL if a compiler does not report using conditions.
  464. :type (or null condition)
  465. :initarg :original-condition
  466. :accessor original-condition)
  467. (severity :type severity
  468. :initarg :severity
  469. :accessor severity)
  470. (message :initarg :message
  471. :accessor message)
  472. ;; Macro expansion history etc. which may be helpful in some cases
  473. ;; but is often very verbose.
  474. (source-context :initarg :source-context
  475. :type (or null string)
  476. :initform nil
  477. :accessor source-context)
  478. (references :initarg :references
  479. :initform nil
  480. :accessor references)
  481. (location :initarg :location
  482. :accessor location)))
  483. (definterface find-external-format (coding-system)
  484. "Return a \"external file format designator\" for CODING-SYSTEM.
  485. CODING-SYSTEM is Emacs-style coding system name (a string),
  486. e.g. \"latin-1-unix\"."
  487. (if (equal coding-system "iso-latin-1-unix")
  488. :default
  489. nil))
  490. (definterface guess-external-format (pathname)
  491. "Detect the external format for the file with name pathname.
  492. Return nil if the file contains no special markers."
  493. ;; Look for a Emacs-style -*- coding: ... -*- or Local Variable: section.
  494. (with-open-file (s pathname :if-does-not-exist nil
  495. :external-format (or (find-external-format "latin-1-unix")
  496. :default))
  497. (if s
  498. (or (let* ((line (read-line s nil))
  499. (p (search "-*-" line)))
  500. (when p
  501. (let* ((start (+ p (length "-*-")))
  502. (end (search "-*-" line :start2 start)))
  503. (when end
  504. (%search-coding line start end)))))
  505. (let* ((len (file-length s))
  506. (buf (make-string (min len 3000))))
  507. (file-position s (- len (length buf)))
  508. (read-sequence buf s)
  509. (let ((start (search "Local Variables:" buf :from-end t))
  510. (end (search "End:" buf :from-end t)))
  511. (and start end (< start end)
  512. (%search-coding buf start end))))))))
  513. (defun %search-coding (str start end)
  514. (let ((p (search "coding:" str :start2 start :end2 end)))
  515. (when p
  516. (incf p (length "coding:"))
  517. (loop while (and (< p end)
  518. (member (aref str p) '(#\space #\tab)))
  519. do (incf p))
  520. (let ((end (position-if (lambda (c) (find c '(#\space #\tab #\newline #\;)))
  521. str :start p)))
  522. (find-external-format (subseq str p end))))))
  523. ;;;; Streams
  524. (definterface make-output-stream (write-string)
  525. "Return a new character output stream.
  526. The stream calls WRITE-STRING when output is ready.")
  527. (definterface make-input-stream (read-string)
  528. "Return a new character input stream.
  529. The stream calls READ-STRING when input is needed.")
  530. (defvar *auto-flush-interval* 0.2)
  531. (defun auto-flush-loop (stream interval &optional receive)
  532. (loop
  533. (when (not (and (open-stream-p stream)
  534. (output-stream-p stream)))
  535. (return nil))
  536. (force-output stream)
  537. (when receive
  538. (receive-if #'identity))
  539. (sleep interval)))
  540. (definterface make-auto-flush-thread (stream)
  541. "Make an auto-flush thread"
  542. (spawn (lambda () (auto-flush-loop stream *auto-flush-interval* nil))
  543. :name "auto-flush-thread"))
  544. ;;;; Documentation
  545. (definterface arglist (name)
  546. "Return the lambda list for the symbol NAME. NAME can also be
  547. a lisp function object, on lisps which support this.
  548. The result can be a list or the :not-available keyword if the
  549. arglist cannot be determined."
  550. (declare (ignore name))
  551. :not-available)
  552. (defgeneric declaration-arglist (decl-identifier)
  553. (:documentation
  554. "Return the argument list of the declaration specifier belonging to the
  555. declaration identifier DECL-IDENTIFIER. If the arglist cannot be determined,
  556. the keyword :NOT-AVAILABLE is returned.
  557. The different SWANK backends can specialize this generic function to
  558. include implementation-dependend declaration specifiers, or to provide
  559. additional information on the specifiers defined in ANSI Common Lisp.")
  560. (:method (decl-identifier)
  561. (case decl-identifier
  562. (dynamic-extent '(&rest variables))
  563. (ignore '(&rest variables))
  564. (ignorable '(&rest variables))
  565. (special '(&rest variables))
  566. (inline '(&rest function-names))
  567. (notinline '(&rest function-names))
  568. (declaration '(&rest names))
  569. (optimize '(&any compilation-speed debug safety space speed))
  570. (type '(type-specifier &rest args))
  571. (ftype '(type-specifier &rest function-names))
  572. (otherwise
  573. (flet ((typespec-p (symbol)
  574. (member :type (describe-symbol-for-emacs symbol))))
  575. (cond ((and (symbolp decl-identifier) (typespec-p decl-identifier))
  576. '(&rest variables))
  577. ((and (listp decl-identifier)
  578. (typespec-p (first decl-identifier)))
  579. '(&rest variables))
  580. (t :not-available)))))))
  581. (defgeneric type-specifier-arglist (typespec-operator)
  582. (:documentation
  583. "Return the argument list of the type specifier belonging to
  584. TYPESPEC-OPERATOR.. If the arglist cannot be determined, the keyword
  585. :NOT-AVAILABLE is returned.
  586. The different SWANK backends can specialize this generic function to
  587. include implementation-dependend declaration specifiers, or to provide
  588. additional information on the specifiers defined in ANSI Common Lisp.")
  589. (:method (typespec-operator)
  590. (declare (special *type-specifier-arglists*)) ; defined at end of file.
  591. (typecase typespec-operator
  592. (symbol (or (cdr (assoc typespec-operator *type-specifier-arglists*))
  593. :not-available))
  594. (t :not-available))))
  595. (definterface type-specifier-p (symbol)
  596. "Determine if SYMBOL is a type-specifier."
  597. (or (documentation symbol 'type)
  598. (not (eq (type-specifier-arglist symbol) :not-available))))
  599. (definterface function-name (function)
  600. "Return the name of the function object FUNCTION.
  601. The result is either a symbol, a list, or NIL if no function name is
  602. available."
  603. (declare (ignore function))
  604. nil)
  605. (definterface valid-function-name-p (form)
  606. "Is FORM syntactically valid to name a function?
  607. If true, FBOUNDP should not signal a type-error for FORM."
  608. (flet ((length=2 (list)
  609. (and (not (null (cdr list))) (null (cddr list)))))
  610. (or (symbolp form)
  611. (and (consp form) (length=2 form)
  612. (eq (first form) 'setf) (symbolp (second form))))))
  613. (definterface macroexpand-all (form &optional env)
  614. "Recursively expand all macros in FORM.
  615. Return the resulting form.")
  616. (definterface compiler-macroexpand-1 (form &optional env)
  617. "Call the compiler-macro for form.
  618. If FORM is a function call for which a compiler-macro has been
  619. defined, invoke the expander function using *macroexpand-hook* and
  620. return the results and T. Otherwise, return the original form and
  621. NIL."
  622. (let ((fun (and (consp form)
  623. (valid-function-name-p (car form))
  624. (compiler-macro-function (car form) env))))
  625. (if fun
  626. (let ((result (funcall *macroexpand-hook* fun form env)))
  627. (values result (not (eq result form))))
  628. (values form nil))))
  629. (definterface compiler-macroexpand (form &optional env)
  630. "Repetitively call `compiler-macroexpand-1'."
  631. (labels ((frob (form expanded)
  632. (multiple-value-bind (new-form newly-expanded)
  633. (compiler-macroexpand-1 form env)
  634. (if newly-expanded
  635. (frob new-form t)
  636. (values new-form expanded)))))
  637. (frob form env)))
  638. (defmacro with-collected-macro-forms
  639. ((forms &optional result) instrumented-form &body body)
  640. "Collect macro forms by locally binding *MACROEXPAND-HOOK*.
  641. Evaluates INSTRUMENTED-FORM and collects any forms which undergo
  642. macro-expansion into a list. Then evaluates BODY with FORMS bound to
  643. the list of forms, and RESULT (optionally) bound to the value of
  644. INSTRUMENTED-FORM."
  645. (assert (and (symbolp forms) (not (null forms))))
  646. (assert (symbolp result))
  647. (let ((result-symbol (or result (gensym))))
  648. `(call-with-collected-macro-forms
  649. (lambda (,forms ,result-symbol)
  650. (declare (ignore ,@(and (not result)
  651. `(,result-symbol))))
  652. ,@body)
  653. (lambda () ,instrumented-form))))
  654. (defun call-with-collected-macro-forms (body-fn instrumented-fn)
  655. (let ((return-value nil)
  656. (collected-forms '()))
  657. (let* ((real-macroexpand-hook *macroexpand-hook*)
  658. (*macroexpand-hook*
  659. (lambda (macro-function form environment)
  660. (let ((result (funcall real-macroexpand-hook
  661. macro-function form environment)))
  662. (unless (eq result form)
  663. (push form collected-forms))
  664. result))))
  665. (setf return-value (funcall instrumented-fn)))
  666. (funcall body-fn collected-forms return-value)))
  667. (definterface collect-macro-forms (form &optional env)
  668. "Collect subforms of FORM which undergo (compiler-)macro expansion.
  669. Returns two values: a list of macro forms and a list of compiler macro
  670. forms."
  671. (with-collected-macro-forms (macro-forms expansion)
  672. (ignore-errors (macroexpand-all form env))
  673. (with-collected-macro-forms (compiler-macro-forms)
  674. (handler-bind ((warning #'muffle-warning))
  675. (ignore-errors
  676. (compile nil `(lambda () ,expansion))))
  677. (values macro-forms compiler-macro-forms))))
  678. (definterface format-string-expand (control-string)
  679. "Expand the format string CONTROL-STRING."
  680. (macroexpand `(formatter ,control-string)))
  681. (definterface describe-symbol-for-emacs (symbol)
  682. "Return a property list describing SYMBOL.
  683. The property list has an entry for each interesting aspect of the
  684. symbol. The recognised keys are:
  685. :VARIABLE :FUNCTION :SETF :SPECIAL-OPERATOR :MACRO :COMPILER-MACRO
  686. :TYPE :CLASS :ALIEN-TYPE :ALIEN-STRUCT :ALIEN-UNION :ALIEN-ENUM
  687. The value of each property is the corresponding documentation string,
  688. or NIL (or the obsolete :NOT-DOCUMENTED). It is legal to include keys
  689. not listed here (but slime-print-apropos in Emacs must know about
  690. them).
  691. Properties should be included if and only if they are applicable to
  692. the symbol. For example, only (and all) fbound symbols should include
  693. the :FUNCTION property.
  694. Example:
  695. \(describe-symbol-for-emacs 'vector)
  696. => (:CLASS :NOT-DOCUMENTED
  697. :TYPE :NOT-DOCUMENTED
  698. :FUNCTION \"Constructs a simple-vector from the given objects.\")")
  699. (definterface describe-definition (name type)
  700. "Describe the definition NAME of TYPE.
  701. TYPE can be any value returned by DESCRIBE-SYMBOL-FOR-EMACS.
  702. Return a documentation string, or NIL if none is available.")
  703. ;;;; Debugging
  704. (definterface install-debugger-globally (function)
  705. "Install FUNCTION as the debugger for all threads/processes. This
  706. usually involves setting *DEBUGGER-HOOK* and, if the implementation
  707. permits, hooking into BREAK as well."
  708. (setq *debugger-hook* function))
  709. (definterface call-with-debugging-environment (debugger-loop-fn)
  710. "Call DEBUGGER-LOOP-FN in a suitable debugging environment.
  711. This function is called recursively at each debug level to invoke the
  712. debugger loop. The purpose is to setup any necessary environment for
  713. other debugger callbacks that will be called within the debugger loop.
  714. For example, this is a reasonable place to compute a backtrace, switch
  715. to safe reader/printer settings, and so on.")
  716. (definterface call-with-debugger-hook (hook fun)
  717. "Call FUN and use HOOK as debugger hook. HOOK can be NIL.
  718. HOOK should be called for both BREAK and INVOKE-DEBUGGER."
  719. (let ((*debugger-hook* hook))
  720. (funcall fun)))
  721. (define-condition sldb-condition (condition)
  722. ((original-condition
  723. :initarg :original-condition
  724. :accessor original-condition))
  725. (:report (lambda (condition stream)
  726. (format stream "Condition in debugger code~@[: ~A~]"
  727. (original-condition condition))))
  728. (:documentation
  729. "Wrapper for conditions that should not be debugged.
  730. When a condition arises from the internals of the debugger, it is not
  731. desirable to debug it -- we'd risk entering an endless loop trying to
  732. debug the debugger! Instead, such conditions can be reported to the
  733. user without (re)entering the debugger by wrapping them as
  734. `sldb-condition's."))
  735. ;;; The following functions in this section are supposed to be called
  736. ;;; within the dynamic contour of CALL-WITH-DEBUGGING-ENVIRONMENT only.
  737. (definterface compute-backtrace (start end)
  738. "Returns a backtrace of the condition currently being debugged,
  739. that is an ordered list consisting of frames. ``Ordered list''
  740. means that an integer I can be mapped back to the i-th frame of this
  741. backtrace.
  742. START and END are zero-based indices constraining the number of frames
  743. returned. Frame zero is defined as the frame which invoked the
  744. debugger. If END is nil, return the frames from START to the end of
  745. the stack.")
  746. (definterface print-frame (frame stream)
  747. "Print frame to stream.")
  748. (definterface frame-restartable-p (frame)
  749. "Is the frame FRAME restartable?.
  750. Return T if `restart-frame' can safely be called on the frame."
  751. (declare (ignore frame))
  752. nil)
  753. (definterface frame-source-location (frame-number)
  754. "Return the source location for the frame associated to FRAME-NUMBER.")
  755. (definterface frame-catch-tags (frame-number)
  756. "Return a list of catch tags for being printed in a debugger stack
  757. frame."
  758. (declare (ignore frame-number))
  759. '())
  760. (definterface frame-locals (frame-number)
  761. "Return a list of ((&key NAME ID VALUE) ...) where each element of
  762. the list represents a local variable in the stack frame associated to
  763. FRAME-NUMBER.
  764. NAME, a symbol; the name of the local variable.
  765. ID, an integer; used as primary key for the local variable, unique
  766. relatively to the frame under operation.
  767. value, an object; the value of the local variable.")
  768. (definterface frame-var-value (frame-number var-id)
  769. "Return the value of the local variable associated to VAR-ID
  770. relatively to the frame associated to FRAME-NUMBER.")
  771. (definterface disassemble-frame (frame-number)
  772. "Disassemble the code for the FRAME-NUMBER.
  773. The output should be written to standard output.
  774. FRAME-NUMBER is a non-negative integer.")
  775. (definterface eval-in-frame (form frame-number)
  776. "Evaluate a Lisp form in the lexical context of a stack frame
  777. in the debugger.
  778. FRAME-NUMBER must be a positive integer with 0 indicating the
  779. frame which invoked the debugger.
  780. The return value is the result of evaulating FORM in the
  781. appropriate context.")
  782. (definterface frame-package (frame-number)
  783. "Return the package corresponding to the frame at FRAME-NUMBER.
  784. Return nil if the backend can't figure it out."
  785. (declare (ignore frame-number))
  786. nil)
  787. (definterface frame-call (frame-number)
  788. "Return a string representing a call to the entry point of a frame.")
  789. (definterface return-from-frame (frame-number form)
  790. "Unwind the stack to the frame FRAME-NUMBER and return the value(s)
  791. produced by evaluating FORM in the frame context to its caller.
  792. Execute any clean-up code from unwind-protect forms above the frame
  793. during unwinding.
  794. Return a string describing the error if it's not possible to return
  795. from the frame.")
  796. (definterface restart-frame (frame-number)
  797. "Restart execution of the frame FRAME-NUMBER with the same arguments
  798. as it was called originally.")
  799. (definterface print-condition (condition stream)
  800. "Print a condition for display in SLDB."
  801. (princ condition stream))
  802. (definterface condition-extras (condition)
  803. "Return a list of extra for the debugger.
  804. The allowed elements are of the form:
  805. (:SHOW-FRAME-SOURCE frame-number)
  806. (:REFERENCES &rest refs)
  807. "
  808. (declare (ignore condition))
  809. '())
  810. (definterface gdb-initial-commands ()
  811. "List of gdb commands supposed to be executed first for the
  812. ATTACH-GDB restart."
  813. nil)
  814. (definterface activate-stepping (frame-number)
  815. "Prepare the frame FRAME-NUMBER for stepping.")
  816. (definterface sldb-break-on-return (frame-number)
  817. "Set a breakpoint in the frame FRAME-NUMBER.")
  818. (definterface sldb-break-at-start (symbol)
  819. "Set a breakpoint on the beginning of the function for SYMBOL.")
  820. (definterface sldb-stepper-condition-p (condition)
  821. "Return true if SLDB was invoked due to a single-stepping condition,
  822. false otherwise. "
  823. (declare (ignore condition))
  824. nil)
  825. (definterface sldb-step-into ()
  826. "Step into the current single-stepper form.")
  827. (definterface sldb-step-next ()
  828. "Step to the next form in the current function.")
  829. (definterface sldb-step-out ()
  830. "Stop single-stepping temporarily, but resume it once the current function
  831. returns.")
  832. ;;;; Definition finding
  833. (defstruct (location (:type list)
  834. (:constructor make-location
  835. (buffer position &optional hints)))
  836. (type :location)
  837. buffer position
  838. ;; Hints is a property list optionally containing:
  839. ;; :snippet SOURCE-TEXT
  840. ;; This is a snippet of the actual source text at the start of
  841. ;; the definition, which could be used in a text search.
  842. hints)
  843. (defmacro converting-errors-to-error-location (&body body)
  844. "Catches errors during BODY and converts them to an error location."
  845. (let ((gblock (gensym "CONVERTING-ERRORS+")))
  846. `(block ,gblock
  847. (handler-bind ((error
  848. #'(lambda (e)
  849. (if *debug-swank-backend*
  850. nil ;decline
  851. (return-from ,gblock
  852. (make-error-location e))))))
  853. ,@body))))
  854. (defun make-error-location (datum &rest args)
  855. (cond ((typep datum 'condition)
  856. `(:error ,(format nil "Error: ~A" datum)))
  857. ((symbolp datum)
  858. `(:error ,(format nil "Error: ~A"
  859. (apply #'make-condition datum args))))
  860. (t
  861. (assert (stringp datum))
  862. `(:error ,(apply #'format nil datum args)))))
  863. (definterface find-definitions (name)
  864. "Return a list ((DSPEC LOCATION) ...) for NAME's definitions.
  865. NAME is a \"definition specifier\".
  866. DSPEC is a \"definition specifier\" describing the
  867. definition, e.g., FOO or (METHOD FOO (STRING NUMBER)) or
  868. \(DEFVAR FOO).
  869. LOCATION is the source location for the definition.")
  870. (definterface find-source-location (object)
  871. "Returns the source location of OBJECT, or NIL.
  872. That is the source location of the underlying datastructure of
  873. OBJECT. E.g. on a STANDARD-OBJECT, the source location of the
  874. respective DEFCLASS definition is returned, on a STRUCTURE-CLASS the
  875. respective DEFSTRUCT definition, and so on."
  876. ;; This returns one source location and not a list of locations. It's
  877. ;; supposed to return the location of the DEFGENERIC definition on
  878. ;; #'SOME-GENERIC-FUNCTION.
  879. (declare (ignore object))
  880. (make-error-location "FIND-SOURCE-LOCATION is not yet implemented on ~
  881. this implementation."))
  882. (definterface buffer-first-change (filename)
  883. "Called for effect the first time FILENAME's buffer is modified.
  884. CMUCL/SBCL use this to cache the unmodified file and use the
  885. unmodified text to improve the precision of source locations."
  886. (declare (ignore filename))
  887. nil)
  888. ;;;; XREF
  889. (definterface who-calls (function-name)
  890. "Return the call sites of FUNCTION-NAME (a symbol).
  891. The results is a list ((DSPEC LOCATION) ...)."
  892. (declare (ignore function-name))
  893. :not-implemented)
  894. (definterface calls-who (function-name)
  895. "Return the call sites of FUNCTION-NAME (a symbol).
  896. The results is a list ((DSPEC LOCATION) ...)."
  897. (declare (ignore function-name))
  898. :not-implemented)
  899. (definterface who-references (variable-name)
  900. "Return the locations where VARIABLE-NAME (a symbol) is referenced.
  901. See WHO-CALLS for a description of the return value."
  902. (declare (ignore variable-name))
  903. :not-implemented)
  904. (definterface who-binds (variable-name)
  905. "Return the locations where VARIABLE-NAME (a symbol) is bound.
  906. See WHO-CALLS for a description of the return value."
  907. (declare (ignore variable-name))
  908. :not-implemented)
  909. (definterface who-sets (variable-name)
  910. "Return the locations where VARIABLE-NAME (a symbol) is set.
  911. See WHO-CALLS for a description of the return value."
  912. (declare (ignore variable-name))
  913. :not-implemented)
  914. (definterface who-macroexpands (macro-name)
  915. "Return the locations where MACRO-NAME (a symbol) is expanded.
  916. See WHO-CALLS for a description of the return value."
  917. (declare (ignore macro-name))
  918. :not-implemented)
  919. (definterface who-specializes (class-name)
  920. "Return the locations where CLASS-NAME (a symbol) is specialized.
  921. See WHO-CALLS for a description of the return value."
  922. (declare (ignore class-name))
  923. :not-implemented)
  924. ;;; Simpler variants.
  925. (definterface list-callers (function-name)
  926. "List the callers of FUNCTION-NAME.
  927. This function is like WHO-CALLS except that it is expected to use
  928. lower-level means. Whereas WHO-CALLS is usually implemented with
  929. special compiler support, LIST-CALLERS is usually implemented by
  930. groveling for constants in function objects throughout the heap.
  931. The return value is as for WHO-CALLS.")
  932. (definterface list-callees (function-name)
  933. "List the functions called by FUNCTION-NAME.
  934. See LIST-CALLERS for a description of the return value.")
  935. ;;;; Profiling
  936. ;;; The following functions define a minimal profiling interface.
  937. (definterface profile (fname)
  938. "Marks symbol FNAME for profiling.")
  939. (definterface profiled-functions ()
  940. "Returns a list of profiled functions.")
  941. (definterface unprofile (fname)
  942. "Marks symbol FNAME as not profiled.")
  943. (definterface unprofile-all ()
  944. "Marks all currently profiled functions as not profiled."
  945. (dolist (f (profiled-functions))
  946. (unprofile f)))
  947. (definterface profile-report ()
  948. "Prints profile report.")
  949. (definterface profile-reset ()
  950. "Resets profile counters.")
  951. (definterface profile-package (package callers-p methods)
  952. "Wrap profiling code around all functions in PACKAGE. If a function
  953. is already profiled, then unprofile and reprofile (useful to notice
  954. function redefinition.)
  955. If CALLERS-P is T names have counts of the most common calling
  956. functions recorded.
  957. When called with arguments :METHODS T, profile all methods of all
  958. generic functions having names in the given package. Generic functions
  959. themselves, that is, their dispatch functions, are left alone.")
  960. ;;;; Trace
  961. (definterface toggle-trace (spec)
  962. "Toggle tracing of the function(s) given with SPEC.
  963. SPEC can be:
  964. (setf NAME) ; a setf function
  965. (:defmethod NAME QUALIFIER... (SPECIALIZER...)) ; a specific method
  966. (:defgeneric NAME) ; a generic function with all methods
  967. (:call CALLER CALLEE) ; trace calls from CALLER to CALLEE.
  968. (:labels TOPLEVEL LOCAL)
  969. (:flet TOPLEVEL LOCAL) ")
  970. ;;;; Inspector
  971. (defgeneric emacs-inspect (object)
  972. (:documentation
  973. "Explain to Emacs how to inspect OBJECT.
  974. Returns a list specifying how to render the object for inspection.
  975. Every element of the list must be either a string, which will be
  976. inserted into the buffer as is, or a list of the form:
  977. (:value object &optional format) - Render an inspectable
  978. object. If format is provided it must be a string and will be
  979. rendered in place of the value, otherwise use princ-to-string.
  980. (:newline) - Render a \\n
  981. (:action label lambda &key (refresh t)) - Render LABEL (a text
  982. string) which when clicked will call LAMBDA. If REFRESH is
  983. non-NIL the currently inspected object will be re-inspected
  984. after calling the lambda.
  985. "))
  986. (defmethod emacs-inspect ((object t))
  987. "Generic method for inspecting any kind of object.
  988. Since we don't know how to deal with OBJECT we simply dump the
  989. output of CL:DESCRIBE."
  990. `("Type: " (:value ,(type-of object)) (:newline)
  991. "Don't know how to inspect the object, dumping output of CL:DESCRIBE:"
  992. (:newline) (:newline)
  993. ,(with-output-to-string (desc) (describe object desc))))
  994. (definterface eval-context (object)
  995. "Return a list of bindings corresponding to OBJECT's slots."
  996. (declare (ignore object))
  997. '())
  998. ;;; Utilities for inspector methods.
  999. ;;;
  1000. (defun label-value-line (label value &key (newline t))
  1001. "Create a control list which prints \"LABEL: VALUE\" in the inspector.
  1002. If NEWLINE is non-NIL a `(:newline)' is added to the result."
  1003. (list* (princ-to-string label) ": " `(:value ,value)
  1004. (if newline '((:newline)) nil)))
  1005. (defmacro label-value-line* (&rest label-values)
  1006. ` (append ,@(loop for (label value) in label-values
  1007. collect `(label-value-line ,label ,value))))
  1008. (definterface describe-primitive-type (object)
  1009. "Return a string describing the primitive type of object."
  1010. (declare (ignore object))
  1011. "N/A")
  1012. ;;;; Multithreading
  1013. ;;;
  1014. ;;; The default implementations are sufficient for non-multiprocessing
  1015. ;;; implementations.
  1016. (definterface initialize-multiprocessing (continuation)
  1017. "Initialize multiprocessing, if necessary and then invoke CONTINUATION.
  1018. Depending on the impleimentaion, this function may never return."
  1019. (funcall continuation))
  1020. (definterface spawn (fn &key name)
  1021. "Create a new thread to call FN.")
  1022. (definterface thread-id (thread)
  1023. "Return an Emacs-parsable object to identify THREAD.
  1024. Ids should be comparable with equal, i.e.:
  1025. (equal (thread-id <t1>) (thread-id <t2>)) <==> (eq <t1> <t2>)"
  1026. thread)
  1027. (definterface find-thread (id)
  1028. "Return the thread for ID.
  1029. ID should be an id previously obtained with THREAD-ID.
  1030. Can return nil if the thread no longer exists."
  1031. (declare (ignore id))
  1032. (current-thread))
  1033. (definterface thread-name (thread)
  1034. "Return the name of THREAD.
  1035. Thread names are short strings meaningful to the user. They do not
  1036. have to be unique."
  1037. (declare (ignore thread))
  1038. "The One True Thread")
  1039. (definterface thread-status (thread)
  1040. "Return a string describing THREAD's state."
  1041. (declare (ignore thread))
  1042. "")
  1043. (definterface thread-attributes (thread)
  1044. "Return a plist of implementation-dependent attributes for THREAD"
  1045. (declare (ignore thread))
  1046. '())
  1047. (definterface current-thread ()
  1048. "Return the currently executing thread."
  1049. 0)
  1050. (definterface all-threads ()
  1051. "Return a fresh list of all threads."
  1052. '())
  1053. (definterface thread-alive-p (thread)
  1054. "Test if THREAD is termintated."
  1055. (member thread (all-threads)))
  1056. (definterface interrupt-thread (thread fn)
  1057. "Cause THREAD to execute FN.")
  1058. (definterface kill-thread (thread)
  1059. "Terminate THREAD immediately.
  1060. Don't execute unwind-protected sections, don't raise conditions.
  1061. (Do not pass go, do not collect $200.)"
  1062. (declare (ignore thread))
  1063. nil)
  1064. (definterface send (thread object)
  1065. "Send OBJECT to thread THREAD."
  1066. (declare (ignore thread))
  1067. object)
  1068. (definterface receive (&optional timeout)
  1069. "Return the next message from current thread's mailbox."
  1070. (receive-if (constantly t) timeout))
  1071. (definterface receive-if (predicate &optional timeout)
  1072. "Return the first message satisfiying PREDICATE.")
  1073. (definterface wake-thread (thread)
  1074. "Trigger a call to CHECK-SLIME-INTERRUPTS in THREAD without using
  1075. asynchronous interrupts."
  1076. (declare (ignore thread))
  1077. ;; Doesn't have to implement this if RECEIVE-IF periodically calls
  1078. ;; CHECK-SLIME-INTERRUPTS, but that's energy inefficient
  1079. nil)
  1080. (definterface register-thread (name thread)
  1081. "Associate the thread THREAD with the symbol NAME.
  1082. The thread can then be retrieved with `find-registered'.
  1083. If THREAD is nil delete the association."
  1084. (declare (ignore name thread))
  1085. nil)
  1086. (definterface find-registered (name)
  1087. "Find the thread that was registered for the symbol NAME.
  1088. Return nil if the no thread was registred or if the tread is dead."
  1089. (declare (ignore name))
  1090. nil)
  1091. (definterface set-default-initial-binding (var form)
  1092. "Initialize special variable VAR by default with FORM.
  1093. Some implementations initialize certain variables in each newly
  1094. created thread. This function sets the form which is used to produce
  1095. the initial value."
  1096. (set var (eval form)))
  1097. ;; List of delayed interrupts.
  1098. ;; This should only have thread-local bindings, so no init form.
  1099. (defvar *pending-slime-interrupts*)
  1100. (defun check-slime-interrupts ()
  1101. "Execute pending interrupts if any.
  1102. This should be called periodically in operations which
  1103. can take a long time to complete.
  1104. Return a boolean indicating whether any interrupts was processed."
  1105. (when (and (boundp '*pending-slime-interrupts*)
  1106. *pending-slime-interrupts*)
  1107. (funcall (pop *pending-slime-interrupts*))
  1108. t))
  1109. (defvar *interrupt-queued-handler* nil
  1110. "Function to call on queued interrupts.
  1111. Interrupts get queued when an interrupt occurs while interrupt
  1112. handling is disabled.
  1113. Backends can use this function to abort slow operations.")
  1114. (definterface wait-for-input (streams &optional timeout)
  1115. "Wait for input on a list of streams. Return those that are ready.
  1116. STREAMS is a list of streams
  1117. TIMEOUT nil, t, or real number. If TIMEOUT is t, return those streams
  1118. which are ready (or have reached end-of-file) without waiting.
  1119. If TIMEOUT is a number and no streams is ready after TIMEOUT seconds,
  1120. return nil.
  1121. Return :interrupt if an interrupt occurs while waiting."
  1122. (declare (ignore streams timeout))
  1123. ;; Invoking the slime debugger will just endlessly loop.
  1124. (call-with-debugger-hook
  1125. nil
  1126. (lambda ()
  1127. (error "~s not implemented. Check if ~s = ~s is supported by the implementation."
  1128. 'wait-for-input 'swank:*communication-style* swank:*communication-style*))))
  1129. ;;;; Locks
  1130. ;; Please use locks only in swank-gray.lisp. Locks are too low-level
  1131. ;; for our taste.
  1132. (definterface make-lock (&key name)
  1133. "Make a lock for thread synchronization.
  1134. Only one thread may hold the lock (via CALL-WITH-LOCK-HELD) at a time
  1135. but that thread may hold it more than once."
  1136. (declare (ignore name))
  1137. :null-lock)
  1138. (definterface call-with-lock-held (lock function)
  1139. "Call FUNCTION with LOCK held, queueing if necessary."
  1140. (declare (ignore lock)
  1141. (type function function))
  1142. (funcall function))
  1143. ;;;; Weak datastructures
  1144. (definterface make-weak-key-hash-table (&rest args)
  1145. "Like MAKE-HASH-TABLE, but weak w.r.t. the keys."
  1146. (apply #'make-hash-table args))
  1147. (definterface make-weak-value-hash-table (&rest args)
  1148. "Like MAKE-HASH-TABLE, but weak w.r.t. the values."
  1149. (apply #'make-hash-table args))
  1150. (definterface hash-table-weakness (hashtable)
  1151. "Return nil or one of :key :value :key-or-value :key-and-value"
  1152. (declare (ignore hashtable))
  1153. nil)
  1154. ;;;; Floating point
  1155. (definterface float-nan-p (float)
  1156. "Return true if FLOAT is a NaN value (Not a Number)."
  1157. ;; When the float type implements IEEE-754 floats, two NaN values
  1158. ;; are never equal; when the implementation does not support NaN,
  1159. ;; the predicate should return false. An implementation can
  1160. ;; implement comparison with "unordered-signaling predicates", which
  1161. ;; emit floating point exceptions.
  1162. (handler-case (not (= float float))
  1163. ;; Comparisons never signal an exception other than the invalid
  1164. ;; operation exception (5.11 Details of comparison predicates).
  1165. (floating-point-invalid-operation () t)))
  1166. (definterface float-infinity-p (float)
  1167. "Return true if FLOAT is positive or negative infinity."
  1168. (not (< most-negative-long-float
  1169. float
  1170. most-positive-long-float)))
  1171. ;;;; Character names
  1172. (definterface character-completion-set (prefix matchp)
  1173. "Return a list of names of characters that match PREFIX."
  1174. ;; Handle the standard and semi-standard characters.
  1175. (loop for name in '("Newline" "Space" "Tab" "Page" "Rubout"
  1176. "Linefeed" "Return" "Backspace")
  1177. when (funcall matchp prefix name)
  1178. collect name))
  1179. (defparameter *type-specifier-arglists*
  1180. '((and . (&rest type-specifiers))
  1181. (array . (&optional element-type dimension-spec))
  1182. (base-string . (&optional size))
  1183. (bit-vector . (&optional size))
  1184. (complex . (&optional type-specifier))
  1185. (cons . (&optional car-typespec cdr-typespec))
  1186. (double-float . (&optional lower-limit upper-limit))
  1187. (eql . (object))
  1188. (float . (&optional lower-limit upper-limit))
  1189. (function . (&optional arg-typespec value-typespec))
  1190. (integer . (&optional lower-limit upper-limit))
  1191. (long-float . (&optional lower-limit upper-limit))
  1192. (member . (&rest eql-objects))
  1193. (mod . (n))
  1194. (not . (type-specifier))
  1195. (or . (&rest type-specifiers))
  1196. (rational . (&optional lower-limit upper-limit))
  1197. (real . (&optional lower-limit upper-limit))
  1198. (satisfies . (predicate-symbol))
  1199. (short-float . (&optional lower-limit upper-limit))
  1200. (signed-byte . (&optional size))
  1201. (simple-array . (&optional element-type dimension-spec))
  1202. (simple-base-string . (&optional size))
  1203. (simple-bit-vector . (&optional size))
  1204. (simple-string . (&optional size))
  1205. (single-float . (&optional lower-limit upper-limit))
  1206. (simple-vector . (&optional size))
  1207. (string . (&optional size))
  1208. (unsigned-byte . (&optional size))
  1209. (values . (&rest typespecs))
  1210. (vector . (&optional element-type size))
  1211. ))
  1212. ;;; Heap dumps
  1213. (definterface save-image (filename &optional restart-function)
  1214. "Save a heap image to the file FILENAME.
  1215. RESTART-FUNCTION, if non-nil, should be called when the image is loaded.")
  1216. (definterface background-save-image (filename &key restart-function
  1217. completion-function)
  1218. "Request saving a heap image to the file FILENAME.
  1219. RESTART-FUNCTION, if non-nil, should be called when the image is loaded.
  1220. COMPLETION-FUNCTION, if non-nil, should be called after saving the image.")
  1221. (defun deinit-log-output ()
  1222. ;; Can't hang on to an fd-stream from a previous session.
  1223. (setf *log-output* nil))
  1224. ;;;; Wrapping
  1225. (definterface wrap (spec indicator &key before after replace)
  1226. "Intercept future calls to SPEC and surround them in callbacks.
  1227. INDICATOR is a symbol identifying a particular wrapping, and is used
  1228. to differentiate between multiple wrappings.
  1229. Implementations intercept calls to SPEC and call, in this order:
  1230. * the BEFORE callback, if it's provided, with a single argument set to
  1231. the list of arguments passed to the intercepted call;
  1232. * the original definition of SPEC recursively honouring any wrappings
  1233. previously established under different values of INDICATOR. If the
  1234. compatible function REPLACE is provided, call that instead.
  1235. * the AFTER callback, if it's provided, with a single set to the list
  1236. of values returned by the previous call, or, if that call exited
  1237. non-locally, a single descriptive symbol, like :EXITED-NON-LOCALLY."
  1238. (declare (ignore indicator))
  1239. (assert (symbolp spec) nil
  1240. "The default implementation for WRAP allows only simple names")
  1241. (assert (null (get spec 'slime-wrap)) nil
  1242. "The default implementation for WRAP allows a single wrapping")
  1243. (let* ((saved (symbol-function spec))
  1244. (replacement (lambda (&rest args)
  1245. (let (retlist completed)
  1246. (unwind-protect
  1247. (progn
  1248. (when before
  1249. (funcall before args))
  1250. (setq retlist (multiple-value-list
  1251. (apply (or replace
  1252. saved) args)))
  1253. (setq completed t)
  1254. (values-list retlist))
  1255. (when after
  1256. (funcall after (if completed
  1257. retlist
  1258. :exited-non-locally))))))))
  1259. (setf (get spec 'slime-wrap) (list saved replacement))
  1260. (setf (symbol-function spec) replacement))
  1261. spec)
  1262. (definterface unwrap (spec indicator)
  1263. "Remove from SPEC any wrappings tagged with INDICATOR."
  1264. (if (wrapped-p spec indicator)
  1265. (setf (symbol-function spec) (first (get spec 'slime-wrap)))
  1266. (cerror "All right, so I did"
  1267. "Hmmm, ~a is not correctly wrapped, you probably redefined it"
  1268. spec))
  1269. (setf (get spec 'slime-wrap) nil)
  1270. spec)
  1271. (definterface wrapped-p (spec indicator)
  1272. "Returns true if SPEC is wrapped with INDICATOR."
  1273. (declare (ignore indicator))
  1274. (and (symbolp spec)
  1275. (let ((prop-value (get spec 'slime-wrap)))
  1276. (cond ((and prop-value
  1277. (not (eq (second prop-value)
  1278. (symbol-function spec))))
  1279. (warn "~a appears to be incorrectly wrapped" spec)
  1280. nil)
  1281. (prop-value t)
  1282. (t nil)))))