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

Contents of /slime/swank-backend.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5