swank-sbcl.lisp 71.6 KB
Newer Older
1
;;;;; -*- indent-tabs-mode: nil -*-
2 3 4 5 6
;;;
;;; swank-sbcl.lisp --- SLIME backend for SBCL.
;;;
;;; Created 2003, Daniel Barlow <dan@metacircles.com>
;;;
7
;;; This code has been placed in the Public Domain.  All warranties are
8 9
;;; disclaimed.

10
;;; Requires the SB-INTROSPECT contrib.
11 12 13

;;; Administrivia

14 15
(in-package :swank-backend)

16 17
(eval-when (:compile-toplevel :load-toplevel :execute)
  (require 'sb-bsd-sockets)
18
  (require 'sb-introspect)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
19
  (require 'sb-posix)
20 21
  (require 'sb-cltl2)
  (import-from :sb-gray *gray-stream-symbols* :swank-backend))
22

23 24
(declaim (optimize (debug 2) 
                   (sb-c::insert-step-conditions 0)
25
                   (sb-c::insert-debug-catch 0)))
26

Juho Snellman's avatar
Juho Snellman committed
27 28 29 30 31 32
;;; backwards compability tests

(eval-when (:compile-toplevel :load-toplevel :execute)
  ;; Generate a form suitable for testing for stepper support (0.9.17)
  ;; with #+.
  (defun sbcl-with-new-stepper-p ()
33
    (with-symbol 'enable-stepping 'sb-impl))
34 35
  ;; Ditto for weak hash-tables
  (defun sbcl-with-weak-hash-tables ()
36
    (with-symbol 'hash-table-weakness 'sb-ext))
37 38
  ;; And for xref support (1.0.1)
  (defun sbcl-with-xref-p ()
39
    (with-symbol 'who-calls 'sb-introspect))
40 41
  ;; ... for restart-frame support (1.0.2)
  (defun sbcl-with-restart-frame ()
42
    (with-symbol 'frame-has-debug-tag-p 'sb-debug)))
Juho Snellman's avatar
Juho Snellman committed
43

44 45
;;; swank-mop

46
(import-swank-mop-symbols :sb-mop '(:slot-definition-documentation))
47

48
(defun swank-mop:slot-definition-documentation (slot)
49
  (sb-pcl::documentation slot t))
50

Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
51 52 53 54 55 56 57 58 59 60 61
;;; Connection info

(defimplementation lisp-implementation-type-name ()
  "sbcl")

;; Declare return type explicitly to shut up STYLE-WARNINGS about
;; %SAP-ALIEN in ENABLE-SIGIO-ON-FD below.
(declaim (ftype (function () (values (signed-byte 32) &optional)) getpid))
(defimplementation getpid ()
  (sb-posix:getpid))

62 63 64 65 66 67 68 69
;;; UTF8

(defimplementation string-to-utf8 (string)
  (sb-ext:string-to-octets string :external-format :utf8))

(defimplementation utf8-to-string (octets)
  (sb-ext:octets-to-string octets :external-format :utf8))

70 71
;;; TCP Server

72
(defimplementation preferred-communication-style ()
73 74 75
  (cond
    ;; fixme: when SBCL/win32 gains better select() support, remove
    ;; this.
76
    ((member :sb-thread *features*) :spawn)
77
    ((member :win32 *features*) nil)
78
    (t :fd-handler)))
79

80 81 82 83
(defun resolve-hostname (name)
  (car (sb-bsd-sockets:host-ent-addresses
        (sb-bsd-sockets:get-host-by-name name))))

84
(defimplementation create-socket (host port &key backlog)
85 86 87
  (let ((socket (make-instance 'sb-bsd-sockets:inet-socket
			       :type :stream
			       :protocol :tcp)))
88
    (setf (sb-bsd-sockets:sockopt-reuse-address socket) t)
89
    (sb-bsd-sockets:socket-bind socket (resolve-hostname host) port)
90
    (sb-bsd-sockets:socket-listen socket (or backlog 5))
91 92
    socket))

93
(defimplementation local-port (socket)
94 95
  (nth-value 1 (sb-bsd-sockets:socket-name socket)))

96
(defimplementation close-socket (socket)
97
  (sb-sys:invalidate-descriptor (socket-fd socket))
98 99
  (sb-bsd-sockets:socket-close socket))

100
(defimplementation accept-connection (socket &key
101 102
                                      external-format
                                      buffering timeout)
103
  (declare (ignore timeout))
104 105 106 107 108
  (make-socket-io-stream (accept socket) external-format 
                         (ecase buffering
                           ((t :full) :full)
                           ((nil :none) :none)
                           ((:line) :line))))
109

110
#-win32
111 112 113 114
(defimplementation install-sigint-handler (function)
  (sb-sys:enable-interrupt sb-unix:sigint 
                           (lambda (&rest args)
                             (declare (ignore args))
115 116 117 118
                             (sb-sys:invoke-interruption 
                              (lambda ()
                                (sb-sys:with-interrupts 
                                  (funcall function)))))))
119

120 121 122 123
(defvar *sigio-handlers* '()
  "List of (key . fn) pairs to be called on SIGIO.")

(defun sigio-handler (signal code scp)
124 125 126 127
  (declare (ignore signal code scp))
  (mapc (lambda (handler)
          (funcall (the function (cdr handler))))
        *sigio-handlers*))
128 129

(defun set-sigio-handler ()
130
  (sb-sys:enable-interrupt sb-unix:sigio (lambda (signal code scp)
131 132
                                           (sigio-handler signal code scp))))

133
(defun enable-sigio-on-fd (fd)
134
  (sb-posix::fcntl fd sb-posix::f-setfl sb-posix::o-async)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
135 136
  (sb-posix::fcntl fd sb-posix::f-setown (getpid))
  (values))
137

138
(defimplementation add-sigio-handler (socket fn)
139 140 141 142 143
  (set-sigio-handler)
  (let ((fd (socket-fd socket)))
    (enable-sigio-on-fd fd)
    (push (cons fd fn) *sigio-handlers*)))

144
(defimplementation remove-sigio-handlers (socket)
145 146
  (let ((fd (socket-fd socket)))
    (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car))
147
    (sb-sys:invalidate-descriptor fd))
148 149
  (close socket))

150 151 152 153 154 155 156 157 158 159 160 161
(defimplementation add-fd-handler (socket fun)
  (let ((fd (socket-fd socket))
        (handler nil))
    (labels ((add ()
               (setq handler (sb-sys:add-fd-handler fd :input #'run)))
             (run (fd)
               (sb-sys:remove-fd-handler handler) ; prevent recursion
               (unwind-protect 
                    (funcall fun)
                 (when (sb-unix:unix-fstat fd) ; still open?
                   (add)))))
      (add))))
162 163 164 165

(defimplementation remove-fd-handlers (socket)
  (sb-sys:invalidate-descriptor (socket-fd socket)))

166
(defimplementation socket-fd (socket)
167 168 169 170 171
  (etypecase socket
    (fixnum socket)
    (sb-bsd-sockets:socket (sb-bsd-sockets:socket-file-descriptor socket))
    (file-stream (sb-sys:fd-stream-fd socket))))

172 173 174 175 176 177
(defimplementation command-line-args ()
  sb-ext:*posix-argv*)

(defimplementation dup (fd)
  (sb-posix:dup fd))

178 179 180 181 182 183 184 185
(defvar *wait-for-input-called*)

(defimplementation wait-for-input (streams &optional timeout)
  (assert (member timeout '(nil t)))
  (when (boundp '*wait-for-input-called*)
    (setq *wait-for-input-called* t))
  (let ((*wait-for-input-called* nil))
    (loop
186 187 188 189 190 191 192 193 194 195
      (let ((ready (remove-if-not #'input-ready-p streams)))
        (when ready (return ready)))
      (when (check-slime-interrupts)
        (return :interrupt))
      (when *wait-for-input-called*
        (return :interrupt))
      (when timeout
        (return nil))
      (sleep 0.1))))

196 197 198 199 200 201
(defun fd-stream-input-buffer-empty-p (stream)
  (let ((buffer (sb-impl::fd-stream-ibuf stream)))
    (or (not buffer)
        (= (sb-impl::buffer-head buffer)
           (sb-impl::buffer-tail buffer)))))

202 203
#-win32
(defun input-ready-p (stream)
204
  (or (not (fd-stream-input-buffer-empty-p stream))
205
      #+#.(swank-backend:with-symbol 'fd-stream-fd-type 'sb-impl)
206 207
      (eq :regular (sb-impl::fd-stream-fd-type stream))
      (not (sb-impl::sysread-may-block-p stream))))
208 209

#+win32
210 211
(progn
  (defun input-ready-p (stream)
212 213
    (or (not (fd-stream-input-buffer-empty-p stream))
        (handle-listen (sockint::fd->handle (sb-impl::fd-stream-fd stream)))))
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

  (sb-alien:define-alien-routine ("WSACreateEvent" wsa-create-event)
      sb-win32:handle)
  
  (sb-alien:define-alien-routine ("WSACloseEvent" wsa-close-event)
      sb-alien:int 
    (event sb-win32:handle))
  
  (defconstant +fd-read+ #.(ash 1 0))
  (defconstant +fd-close+ #.(ash 1 5))
  
  (sb-alien:define-alien-routine ("WSAEventSelect" wsa-event-select)
      sb-alien:int 
    (fd sb-alien:int) 
    (handle sb-win32:handle)
    (mask sb-alien:long))

  (sb-alien:load-shared-object "kernel32.dll")
  (sb-alien:define-alien-routine ("WaitForSingleObjectEx" 
                                  wait-for-single-object-ex)
      sb-alien:int
    (event sb-win32:handle)
    (milliseconds sb-alien:long)
    (alertable sb-alien:int))

  ;; see SB-WIN32:HANDLE-LISTEN
  (defun handle-listen (handle)
    (sb-alien:with-alien ((avail sb-win32:dword)
                          (buf (array char #.sb-win32::input-record-size)))
      (unless (zerop (sb-win32:peek-named-pipe handle nil 0 nil 
                                               (sb-alien:alien-sap
                                                (sb-alien:addr avail))
                                               nil))
        (return-from handle-listen (plusp avail)))

      (unless (zerop (sb-win32:peek-console-input handle
                                                  (sb-alien:alien-sap buf)
                                                  sb-win32::input-record-size 
                                                  (sb-alien:alien-sap 
                                                   (sb-alien:addr avail))))
        (return-from handle-listen (plusp avail))))

    (let ((event (wsa-create-event)))
      (wsa-event-select handle event (logior +fd-read+ +fd-close+))
      (let ((val (wait-for-single-object-ex event 0 0)))
        (wsa-close-event event)
        (unless (= val -1)
          (return-from handle-listen (zerop val)))))

    nil)

  )
266

267 268 269 270 271 272 273 274
(defvar *external-format-to-coding-system*
  '((:iso-8859-1 
     "latin-1" "latin-1-unix" "iso-latin-1-unix" 
     "iso-8859-1" "iso-8859-1-unix")
    (:utf-8 "utf-8" "utf-8-unix")
    (:euc-jp "euc-jp" "euc-jp-unix")
    (:us-ascii "us-ascii" "us-ascii-unix")))

275 276
;; C.f. R.M.Kreuter in <20536.1219412774@progn.net> on sbcl-general,
;; 2008-08-22.
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
277 278
(defvar *physical-pathname-host* (pathname-host (user-homedir-pathname)))

279
(defimplementation filename-to-pathname (filename)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
280 281
  (sb-ext:parse-native-namestring filename *physical-pathname-host*))

282 283 284
(defimplementation find-external-format (coding-system)
  (car (rassoc-if (lambda (x) (member coding-system x :test #'equal))
                  *external-format-to-coding-system*)))
285

286
(defun make-socket-io-stream (socket external-format buffering)
287 288 289 290 291 292 293 294 295 296 297
  (let ((args `(,@()
                :output t
                :input t
                :element-type ,(if external-format
                                   'character 
                                   '(unsigned-byte 8))
                :buffering ,buffering
                ,@(cond ((and external-format (sb-int:featurep :sb-unicode))
                         `(:external-format ,external-format))
                        (t '()))
                :serve-events ,(eq :fd-handler
298
                                   (swank-value '*communication-style* t))
299 300 301 302
                  ;; SBCL < 1.0.42.43 doesn't support :SERVE-EVENTS
                  ;; argument.
                :allow-other-keys t)))
  (apply #'sb-bsd-sockets:socket-make-stream socket args)))
303

304 305
(defun accept (socket)
  "Like socket-accept, but retry on EAGAIN."
306
  (loop (handler-case
307 308 309
            (return (sb-bsd-sockets:socket-accept socket))
          (sb-bsd-sockets:interrupted-error ()))))

310 311 312

;;;; Support for SBCL syntax

Helmut Eller's avatar
Helmut Eller committed
313 314 315 316 317 318
;;; SBCL's source code is riddled with #! reader macros.  Also symbols
;;; containing `!' have special meaning.  We have to work long and
;;; hard to be able to read the source.  To deal with #! reader
;;; macros, we use a special readtable.  The special symbols are
;;; converted by a condition handler.

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
(defun feature-in-list-p (feature list)
  (etypecase feature
    (symbol (member feature list :test #'eq))
    (cons (flet ((subfeature-in-list-p (subfeature)
		   (feature-in-list-p subfeature list)))
	    (ecase (first feature)
	      (:or  (some  #'subfeature-in-list-p (rest feature)))
	      (:and (every #'subfeature-in-list-p (rest feature)))
	      (:not (destructuring-bind (e) (cdr feature)
                      (not (subfeature-in-list-p e)))))))))

(defun shebang-reader (stream sub-character infix-parameter)
  (declare (ignore sub-character))
  (when infix-parameter
    (error "illegal read syntax: #~D!" infix-parameter))
  (let ((next-char (read-char stream)))
    (unless (find next-char "+-")
      (error "illegal read syntax: #!~C" next-char))
    ;; When test is not satisfied
    ;; FIXME: clearer if order of NOT-P and (NOT NOT-P) were reversed? then
    ;; would become "unless test is satisfied"..
    (when (let* ((*package* (find-package "KEYWORD"))
		 (*read-suppress* nil)
		 (not-p (char= next-char #\-))
		 (feature (read stream)))
	    (if (feature-in-list-p feature *features*)
		not-p
		(not not-p)))
      ;; Read (and discard) a form from input.
      (let ((*read-suppress* t))
	(read stream t nil t))))
 (values))

352
(defvar *shebang-readtable*
353
  (let ((*readtable* (copy-readtable nil)))
354
    (set-dispatch-macro-character #\# #\!
355 356 357 358 359 360 361 362 363 364 365
                                  (lambda (s c n) (shebang-reader s c n))
                                  *readtable*)
    *readtable*))

(defun shebang-readtable ()
  *shebang-readtable*)

(defun sbcl-package-p (package)
  (let ((name (package-name package)))
    (eql (mismatch "SB-" name) 3)))

366
(defun sbcl-source-file-p (filename)
367
  (when filename
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
368
    (loop for (nil pattern) in (logical-pathname-translations "SYS")
369
          thereis (pathname-match-p filename pattern))))
370 371 372 373 374 375

(defun guess-readtable-for-filename (filename)
  (if (sbcl-source-file-p filename)
      (shebang-readtable)
      *readtable*))

376 377
(defvar *debootstrap-packages* t)

378
(defun call-with-debootstrapping (fun)
379
  (handler-bind ((sb-int:bootstrap-package-not-found
380 381 382
                  #'sb-int:debootstrap-package))
    (funcall fun)))

383
(defmacro with-debootstrapping (&body body)
384
  `(call-with-debootstrapping (lambda () ,@body)))
385 386

(defimplementation call-with-syntax-hooks (fn)
387
  (cond ((and *debootstrap-packages*
388 389 390 391 392 393 394 395 396 397
              (sbcl-package-p *package*))
         (with-debootstrapping (funcall fn)))
        (t
         (funcall fn))))

(defimplementation default-readtable-alist ()
  (let ((readtable (shebang-readtable)))
    (loop for p in (remove-if-not #'sbcl-package-p (list-all-packages))
          collect (cons (package-name p) readtable))))

398 399
;;; Utilities

400 401 402 403 404 405 406 407 408
(defun swank-value (name &optional errorp)
  ;; Easy way to refer to symbol values in SWANK, which doesn't yet exist when
  ;; this is file is loaded.
  (let ((symbol (find-symbol (string name) :swank)))
    (if (and symbol (or errorp (boundp symbol)))
        (symbol-value symbol)
        (when errorp
          (error "~S does not exist in SWANK." name)))))

409
#+#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect)
410 411 412
(defimplementation arglist (fname)
  (sb-introspect:function-lambda-list fname))

413
#-#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect)
414
(defimplementation arglist (fname)
415
  (sb-introspect:function-arglist fname))
416

417 418
(defimplementation function-name (f)
  (check-type f function)
419 420
  (sb-impl::%fun-name f))

Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
421 422 423 424
(defmethod declaration-arglist ((decl-identifier (eql 'optimize)))
  (flet ((ensure-list (thing) (if (listp thing) thing (list thing))))
    (let* ((flags (sb-cltl2:declaration-information decl-identifier)))
      (if flags
425 426 427 428 429 430 431 432
          ;; Symbols aren't printed with package qualifiers, but the
          ;; FLAGS would have to be fully qualified when used inside a
          ;; declaration. So we strip those as long as there's no
          ;; better way. (FIXME)
          `(&any ,@(remove-if-not
                    #'(lambda (qualifier)
                        (find-symbol (symbol-name (first qualifier)) :cl))
                    flags :key #'ensure-list))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
433 434
          (call-next-method)))))

435
#+#.(swank-backend:with-symbol 'deftype-lambda-list 'sb-introspect)
436 437 438 439 440
(defmethod type-specifier-arglist :around (typespec-operator)
  (multiple-value-bind (arglist foundp)
      (sb-introspect:deftype-lambda-list typespec-operator)
    (if foundp arglist (call-next-method))))

441

442
(defvar *buffer-name* nil)
443
(defvar *buffer-tmpfile* nil)
444
(defvar *buffer-offset*)
445
(defvar *buffer-substring* nil)
446

447 448 449
(defvar *previous-compiler-condition* nil
  "Used to detect duplicates.")

450 451 452 453 454 455
(defun handle-notification-condition (condition)
  "Handle a condition caused by a compiler warning.
This traps all compiler conditions at a lower-level than using
C:*COMPILER-NOTIFICATION-FUNCTION*. The advantage is that we get to
craft our own error messages, which can omit a lot of redundant
information."
456 457 458 459 460 461
  (unless (or (eq condition *previous-compiler-condition*))
    ;; First resignal warnings, so that outer handlers -- which may choose to
    ;; muffle this -- get a chance to run.
    (when (typep condition 'warning)
      (signal condition))
    (setq *previous-compiler-condition* condition)
462 463
    (signal-compiler-condition (real-condition condition)
                               (sb-c::find-error-context nil))))
464 465 466 467 468 469 470

(defun signal-compiler-condition (condition context)
  (signal (make-condition
           'compiler-condition
           :original-condition condition
           :severity (etypecase condition
                       (sb-ext:compiler-note :note)
471
                       (sb-c:compiler-error  :error)
472
                       (reader-error         :read-error)
473
                       (error                :error)
474 475
                       #+#.(swank-backend:with-symbol redefinition-warning 
                             sb-kernel)
476 477
                       (sb-kernel:redefinition-warning
                                             :redefinition)
478
                       (style-warning        :style-warning)
479 480
                       (warning              :warning))
           :references (condition-references condition)
481 482
           :message (brief-compiler-message-for-emacs condition)
           :source-context (compiler-error-context context)
483
           :location (compiler-note-location condition context))))
484

485 486 487 488 489 490
(defun real-condition (condition)
  "Return the encapsulated condition or CONDITION itself."
  (typecase condition
    (sb-int:encapsulated-condition (sb-int:encapsulated-condition condition))
    (t condition)))

491 492 493 494 495
(defun condition-references (condition)
  (if (typep condition 'sb-int:reference-condition)
      (externalize-reference
       (sb-int:reference-condition-references condition))))

496 497
(defun compiler-note-location (condition context)
  (flet ((bailout ()
498 499
           (return-from compiler-note-location
             (make-error-location "No error location available"))))
500 501 502 503 504 505
    (cond (context
           (locate-compiler-note
            (sb-c::compiler-error-context-file-name context)
            (compiler-source-path context)
            (sb-c::compiler-error-context-original-source context)))
          ((typep condition 'reader-error)
506 507 508 509 510
           (let* ((stream (stream-error-stream condition))
                  (file   (pathname stream)))
             (unless (open-stream-p stream)
               (bailout))
             (if (compiling-from-buffer-p file)
511 512 513
                 ;; The stream position for e.g. "comma not inside
                 ;; backquote" is at the character following the
                 ;; comma, :offset is 0-based, hence the 1-.
514 515
                 (make-location (list :buffer *buffer-name*)
                                (list :offset *buffer-offset*
516
                                      (1- (file-position stream))))
517 518
                 (progn
                   (assert (compiling-from-file-p file))
519
                   ;; No 1- because :position is 1-based.
520 521
                   (make-location (list :file (namestring file))
                                  (list :position (file-position stream)))))))
522
          (t (bailout)))))
523

524
(defun compiling-from-buffer-p (filename)
525 526
  (and *buffer-name*
       ;; The following is to trigger COMPILING-FROM-GENERATED-CODE-P
527 528
       ;; in LOCATE-COMPILER-NOTE, and allows handling nested
       ;; compilation from eg. hitting C-C on (eval-when ... (require ..))).
529 530
       ;;
       ;; PROBE-FILE to handle tempfile directory being a symlink.
531
       (pathnamep filename)
532 533 534
       (let ((true1 (probe-file filename))
             (true2 (probe-file *buffer-tmpfile*)))
         (and true1 (equal true1 true2)))))
535 536

(defun compiling-from-file-p (filename)
537 538
  (and (pathnamep filename)
       (or (null *buffer-name*)
539 540 541 542
           (null *buffer-tmpfile*)
           (let ((true1 (probe-file filename))
                 (true2 (probe-file *buffer-tmpfile*)))
             (not (and true1 (equal true1 true2)))))))
543 544 545 546

(defun compiling-from-generated-code-p (filename source)
  (and (eq filename :lisp) (stringp source)))

547
(defun locate-compiler-note (file source-path source)
548
  (cond ((compiling-from-buffer-p file)
549 550 551 552
         (make-location (list :buffer *buffer-name*)
                        (list :offset  *buffer-offset* 
                              (source-path-string-position
                               source-path *buffer-substring*))))
553
        ((compiling-from-file-p file)
554
         (make-location (list :file (namestring file))
555 556
                        (list :position (1+ (source-path-file-position
                                             source-path file)))))
557
        ((compiling-from-generated-code-p file source)
558 559
         (make-location (list :source-form source)
                        (list :position 1)))
560
        (t
561 562
         (error "unhandled case in compiler note ~S ~S ~S" 
                file source-path source))))
563

564
(defun brief-compiler-message-for-emacs (condition)
565 566 567 568
  "Briefly describe a compiler error for Emacs.
When Emacs presents the message it already has the source popped up
and the source form highlighted. This makes much of the information in
the error-context redundant."
569 570
  (let ((sb-int:*print-condition-references* nil))
    (princ-to-string condition)))
571

572
(defun compiler-error-context (error-context)
573
  "Describe a compiler error for Emacs including context information."
574
  (declare (type (or sb-c::compiler-error-context null) error-context))
575 576 577 578
  (multiple-value-bind (enclosing source)
      (if error-context
          (values (sb-c::compiler-error-context-enclosing-source error-context)
                  (sb-c::compiler-error-context-source error-context)))
579 580 581
    (and (or enclosing source)
         (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~%~}~]"
                 enclosing source))))
582

583
(defun compiler-source-path (context)
584 585 586 587 588 589 590 591 592 593 594
  "Return the source-path for the current compiler error.
Returns NIL if this cannot be determined by examining internal
compiler state."
  (cond ((sb-c::node-p context)
         (reverse
          (sb-c::source-path-original-source
           (sb-c::node-source-path context))))
        ((sb-c::compiler-error-context-p context)
         (reverse
          (sb-c::compiler-error-context-original-source-path context)))))

595
(defimplementation call-with-compilation-hooks (function)
596
  (declare (type function function))
597 598 599 600
  (handler-bind
      ;; N.B. Even though these handlers are called HANDLE-FOO they
      ;; actually decline, i.e. the signalling of the original
      ;; condition continues upward.
601 602 603 604 605
      ((sb-c:fatal-compiler-error #'handle-notification-condition)
       (sb-c:compiler-error       #'handle-notification-condition)
       (sb-ext:compiler-note      #'handle-notification-condition)
       (error                     #'handle-notification-condition)
       (warning                   #'handle-notification-condition))
606
    (funcall function)))
607

608

609
(defvar *trap-load-time-warnings* t)
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
(defun compiler-policy (qualities)
  "Return compiler policy qualities present in the QUALITIES alist.
QUALITIES is an alist with (quality . value)"
  #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext)
  (loop with policy = (sb-ext:restrict-compiler-policy)
        for (quality) in qualities
        collect (cons quality
                      (or (cdr (assoc quality policy))
                          0))))

(defun (setf compiler-policy) (policy)
  (declare (ignorable policy))
  #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext)
  (loop for (qual . value) in policy
        do (sb-ext:restrict-compiler-policy qual value)))

(defmacro with-compiler-policy (policy &body body)
  (let ((current-policy (gensym)))
    `(let ((,current-policy (compiler-policy ,policy)))
       (setf (compiler-policy) ,policy)
       (unwind-protect (progn ,@body)
         (setf (compiler-policy) ,current-policy)))))

634
(defimplementation swank-compile-file (input-file output-file 
635 636
                                       load-p external-format
                                       &key policy)
637
  (multiple-value-bind (output-file warnings-p failure-p)
638 639 640 641
      (with-compiler-policy policy
        (with-compilation-hooks ()
          (compile-file input-file :output-file output-file
                        :external-format external-format)))
642 643 644 645 646 647 648
    (values output-file warnings-p
            (or failure-p
                (when load-p
                  ;; Cache the latest source file for definition-finding.
                  (source-cache-get input-file 
                                    (file-write-date input-file))
                  (not (load output-file)))))))
649

650 651
;;;; compile-string

652 653 654 655 656 657
;;; We copy the string to a temporary file in order to get adequate
;;; semantics for :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL EVAL-WHEN forms
;;; which the previous approach using
;;;     (compile nil `(lambda () ,(read-from-string string)))
;;; did not provide.

658 659
(locally (declare (sb-ext:muffle-conditions sb-ext:compiler-note))

660 661 662 663
(sb-alien:define-alien-routine (#-win32 "tempnam" #+win32 "_tempnam" tempnam)
    sb-alien:c-string
  (dir sb-alien:c-string)
  (prefix sb-alien:c-string))
664

665 666
)

667 668
(defun temp-file-name ()
  "Return a temporary file name to compile strings into."
669
  (tempnam nil nil))
670

671 672
(defimplementation swank-compile-string (string &key buffer position filename
                                         policy)
673 674 675
  (let ((*buffer-name* buffer)
        (*buffer-offset* position)
        (*buffer-substring* string)
676
        (*buffer-tmpfile* (temp-file-name)))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
677 678 679
    (flet ((load-it (filename)
             (when filename (load filename)))
           (compile-it (cont)
680
             (with-compilation-hooks ()
681 682
               (with-compilation-unit
                   (:source-plist (list :emacs-buffer buffer
683
                                        :emacs-filename filename
684
                                        :emacs-string string
685 686 687
                                        :emacs-position position)
                    :source-namestring filename
                    :allow-other-keys t)
688
                 (multiple-value-bind (output-file warningsp failurep)
689
                     (compile-file *buffer-tmpfile* :external-format :utf-8)
690
                   (declare (ignore warningsp))
691 692
                   (unless failurep
                     (funcall cont output-file)))))))
693 694
      (with-open-file (s *buffer-tmpfile* :direction :output :if-exists :error
                         :external-format :utf-8)
695 696
        (write-string string s))
      (unwind-protect
697 698 699 700
           (with-compiler-policy policy
            (if *trap-load-time-warnings*
                (compile-it #'load-it)
                (load-it (compile-it #'identity))))
701
        (ignore-errors
702 703
          (delete-file *buffer-tmpfile*)
          (delete-file (compile-file-pathname *buffer-tmpfile*)))))))
704 705 706

;;;; Definitions

707 708 709 710 711 712 713 714 715 716 717 718
(defparameter *definition-types*
  '(:variable defvar
    :constant defconstant
    :type deftype
    :symbol-macro define-symbol-macro
    :macro defmacro
    :compiler-macro define-compiler-macro
    :function defun
    :generic-function defgeneric
    :method defmethod
    :setf-expander define-setf-expander
    :structure defstruct
719
    :condition define-condition
720 721 722 723 724 725 726 727 728
    :class defclass
    :method-combination define-method-combination
    :package defpackage
    :transform :deftransform
    :optimizer :defoptimizer
    :vop :define-vop
    :source-transform :define-source-transform)
  "Map SB-INTROSPECT definition type names to Slime-friendly forms")

729 730 731 732 733 734 735 736
(defun definition-specifier (type name)
  "Return a pretty specifier for NAME representing a definition of type TYPE."
  (if (and (symbolp name)
           (eq type :function)
           (sb-int:info :function :ir1-convert name))
      :def-ir1-translator
      (getf *definition-types* type)))

737
(defun make-dspec (type name source-location)
738 739 740 741 742 743 744
  (let ((spec (definition-specifier type name))
        (desc (sb-introspect::definition-source-description source-location)))
    (if (eq :define-vop spec)
        ;; The first part of the VOP description is the name of the template
        ;; -- which is actually good information and often long. So elide the
        ;; original name in favor of making the interesting bit more visible.
        ;;
745 746 747 748
        ;; The second part of the VOP description is the associated
        ;; compiler note, or NIL -- which is quite uninteresting and
        ;; confuses the eye when reading the actual name which usually
        ;; has a worthwhile postfix. So drop the note.
749 750
        (list spec (car desc))
        (list* spec name desc))))
751

752 753
(defimplementation find-definitions (name)
  (loop for type in *definition-types* by #'cddr
754 755 756
        for defsrcs = (sb-introspect:find-definition-sources-by-name name type)
        append (loop for defsrc in defsrcs collect
                     (list (make-dspec type name defsrc)
757
                           (converting-errors-to-error-location
758 759
                             (definition-source-for-emacs defsrc
                                 type name))))))
760

Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
761 762 763 764 765 766 767 768 769
(defimplementation find-source-location (obj)
  (flet ((general-type-of (obj)
           (typecase obj
             (method             :method)
             (generic-function   :generic-function)
             (function           :function)
             (structure-class    :structure-class)
             (class              :class)
             (method-combination :method-combination)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
770
             (package            :package)
771
             (condition          :condition)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
772 773 774 775 776
             (structure-object   :structure-object)
             (standard-object    :standard-object)
             (t                  :thing)))
         (to-string (obj)
           (typecase obj
777 778
             ;; Packages are possibly named entities.
             (package (princ-to-string obj)) 
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
779 780 781
             ((or structure-object standard-object condition)
              (with-output-to-string (s)
                (print-unreadable-object (obj s :type t :identity t))))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
782
             (t (princ-to-string obj)))))
783
    (converting-errors-to-error-location
784 785 786 787
      (let ((defsrc (sb-introspect:find-definition-source obj)))
        (definition-source-for-emacs defsrc
                                     (general-type-of obj)
                                     (to-string obj))))))
788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
(defmacro with-definition-source ((&rest names) obj &body body)
  "Like with-slots but works only for structs."
  (flet ((reader (slot)
           ;; Use read-from-string instead of intern so that
           ;; conc-name can be a string such as ext:struct- and not
           ;; cause errors and not force interning ext::struct-
           (read-from-string
            (concatenate 'string "sb-introspect:definition-source-" 
                         (string slot)))))
    (let ((tmp (gensym "OO-")))
      ` (let ((,tmp ,obj))
          (symbol-macrolet
              ,(loop for name in names collect 
                     (typecase name
                       (symbol `(,name (,(reader name) ,tmp)))
                       (cons `(,(first name) (,(reader (second name)) ,tmp)))
                       (t (error "Malformed syntax in WITH-STRUCT: ~A" name))))
            ,@body)))))
807

808
(defun categorize-definition-source (definition-source)
809 810
  (with-definition-source (pathname form-path character-offset plist)
    definition-source
811 812 813 814 815 816 817
    (let ((file-p (and pathname (probe-file pathname)
                       (or form-path character-offset))))
      (cond ((and (getf plist :emacs-buffer) file-p) :buffer-and-file)
            ((getf plist :emacs-buffer) :buffer)
            (file-p :file)
            (pathname :file-without-position)
            (t :invalid)))))
818

819
(defun definition-source-buffer-location (definition-source)
820
  (with-definition-source (form-path character-offset plist) definition-source
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    (destructuring-bind (&key emacs-buffer emacs-position emacs-directory
                              emacs-string &allow-other-keys)
        plist
      (let ((*readtable* (guess-readtable-for-filename emacs-directory)))
        (multiple-value-bind (start end)
            (if form-path
                (with-debootstrapping
                  (source-path-string-position form-path
                                               emacs-string))
                (values character-offset
                        most-positive-fixnum))
          (make-location
           `(:buffer ,emacs-buffer)
           `(:offset ,emacs-position ,start)
           `(:snippet
             ,(subseq emacs-string
                      start
                      (min end (+ start *source-snippet-size*))))))))))

(defun definition-source-file-location (definition-source)
841 842
  (with-definition-source (pathname form-path character-offset plist 
                                    file-write-date) definition-source
843 844 845 846 847 848 849 850 851 852 853 854
    (let* ((namestring (namestring (translate-logical-pathname pathname)))
           (pos (if form-path
                    (source-file-position namestring file-write-date 
                                          form-path)
                    character-offset))
           (snippet (source-hint-snippet namestring file-write-date pos)))
      (make-location `(:file ,namestring)
                     ;; /file positions/ in Common Lisp start from
                     ;; 0, buffer positions in Emacs start from 1.
                     `(:position ,(1+ pos))
                     `(:snippet ,snippet)))))

855 856 857 858 859 860
(defun definition-source-buffer-and-file-location (definition-source)
  (let ((buffer (definition-source-buffer-location definition-source))
        (file (definition-source-file-location definition-source)))
    (make-location (list :buffer-and-file
                         (cadr (location-buffer buffer))
                         (cadr (location-buffer file)))
861 862
                   (location-position buffer)
                   (location-hints buffer))))
863

864
(defun definition-source-for-emacs (definition-source type name)
865 866 867
  (with-definition-source (pathname form-path character-offset plist
                                    file-write-date)
      definition-source
Stas Boukarev's avatar
Stas Boukarev committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    (ecase (categorize-definition-source definition-source)
      (:buffer-and-file
       (definition-source-buffer-and-file-location definition-source))
      (:buffer
       (definition-source-buffer-location definition-source))
      (:file
       (definition-source-file-location definition-source))
      (:file-without-position
       (make-location `(:file ,(namestring 
                                (translate-logical-pathname pathname)))
                      '(:position 1)
                      (when (eql type :function)
                        `(:snippet ,(format nil "(defun ~a " 
                                            (symbol-name name))))))
      (:invalid
       (error "DEFINITION-SOURCE of ~(~A~) ~A did not contain ~
884
               meaningful information."
Stas Boukarev's avatar
Stas Boukarev committed
885
              type name)))))
886 887

(defun source-file-position (filename write-date form-path)
888 889
  (let ((source (get-source-code filename write-date))
        (*readtable* (guess-readtable-for-filename filename)))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
890
    (with-debootstrapping
891
      (source-path-string-position form-path source))))
892

893
(defun source-hint-snippet (filename write-date position)
894
  (read-snippet-from-string (get-source-code filename write-date) position))
895

896 897
(defun function-source-location (function &optional name)
  (declare (type function function))
898 899 900
  (definition-source-for-emacs (sb-introspect:find-definition-source function)
                               :function
                               (or name (function-name function))))
901

902
(defimplementation describe-symbol-for-emacs (symbol)
903 904 905
  "Return a plist describing SYMBOL.
Return NIL if the symbol is unbound."
  (let ((result '()))
906 907 908 909 910
    (flet ((doc (kind)
             (or (documentation symbol kind) :not-documented))
           (maybe-push (property value)
             (when value
               (setf result (list* property value result)))))
911 912 913 914 915 916
      (maybe-push
       :variable (multiple-value-bind (kind recorded-p)
		     (sb-int:info :variable :kind symbol)
		   (declare (ignore kind))
		   (if (or (boundp symbol) recorded-p)
		       (doc 'variable))))
917 918 919 920 921 922 923 924
      (when (fboundp symbol)
	(maybe-push
	 (cond ((macro-function symbol)     :macro)
	       ((special-operator-p symbol) :special-operator)
	       ((typep (fdefinition symbol) 'generic-function)
                :generic-function)
	       (t :function))
	 (doc 'function)))
925 926 927 928 929 930 931
      (maybe-push
       :setf (if (or (sb-int:info :setf :inverse symbol)
		     (sb-int:info :setf :expander symbol))
		 (doc 'setf)))
      (maybe-push
       :type (if (sb-int:info :type :kind symbol)
		 (doc 'type)))
932
      result)))
933

934
(defimplementation describe-definition (symbol type)
935 936
  (case type
    (:variable
937 938 939
     (describe symbol))
    (:function
     (describe (symbol-function symbol)))
940
    (:setf
941 942
     (describe (or (sb-int:info :setf :inverse symbol)
                   (sb-int:info :setf :expander symbol))))
943
    (:class
944
     (describe (find-class symbol)))
945
    (:type
946
     (describe (sb-kernel:values-specifier-type symbol)))))
947 948 949
  
#+#.(swank-backend::sbcl-with-xref-p)
(progn
950
  (defmacro defxref (name &optional fn-name)
951 952 953
    `(defimplementation ,name (what)
       (sanitize-xrefs   
        (mapcar #'source-location-for-xref-data
954 955 956 957
                (,(find-symbol (symbol-name (if fn-name
                                                fn-name
                                                name))
                               "SB-INTROSPECT")
958 959 960 961 962
                  what)))))
  (defxref who-calls)
  (defxref who-binds)
  (defxref who-sets)
  (defxref who-references)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
963
  (defxref who-macroexpands)
964
  #+#.(swank-backend:with-symbol 'who-specializes-directly 'sb-introspect)
965
  (defxref who-specializes who-specializes-directly))
966 967

(defun source-location-for-xref-data (xref-data)
968
  (destructuring-bind (name . defsrc) xref-data
969
    (list name (converting-errors-to-error-location
970
                 (definition-source-for-emacs defsrc 'function name)))))
971

972 973
(defimplementation list-callers (symbol)
  (let ((fn (fdefinition symbol)))
974 975
    (sanitize-xrefs
     (mapcar #'function-dspec (sb-introspect:find-function-callers fn)))))
976 977 978

(defimplementation list-callees (symbol)
  (let ((fn (fdefinition symbol)))
979 980 981
    (sanitize-xrefs
     (mapcar #'function-dspec (sb-introspect:find-function-callees fn)))))

982
(defun sanitize-xrefs (xrefs)
983 984 985
  (remove-duplicates
   (remove-if (lambda (f)
                (member f (ignored-xref-function-names)))
986 987 988 989 990 991 992 993 994 995
              (loop for entry in xrefs
                    for name = (car entry)
                    collect (if (and (consp name)
                                     (member (car name)
                                             '(sb-pcl::fast-method
                                               sb-pcl::slow-method
                                               sb-pcl::method)))
                                (cons (cons 'defmethod (cdr name))
                                      (cdr entry))
                                entry))
996 997 998 999 1000 1001 1002 1003 1004 1005
              :key #'car)
   :test (lambda (a b)
           (and (eq (first a) (first b))
                (equal (second a) (second b))))))

(defun ignored-xref-function-names ()
  #-#.(swank-backend::sbcl-with-new-stepper-p)
  '(nil sb-c::step-form sb-c::step-values)
  #+#.(swank-backend::sbcl-with-new-stepper-p)
  '(nil))
Juho Snellman's avatar
Juho Snellman committed
1006

1007 1008 1009
(defun function-dspec (fn)
  "Describe where the function FN was defined.
Return a list of the form (NAME LOCATION)."
1010
  (let ((name (function-name fn)))
1011
    (list name (converting-errors-to-error-location
1012
                 (function-source-location fn name)))))
1013

Dan Barlow's avatar
Dan Barlow committed
1014
;;; macroexpansion
1015

1016
(defimplementation macroexpand-all (form)
1017 1018 1019
  (let ((sb-walker:*walk-form-expand-macros-p* t))
    (sb-walker:walk-form form)))

1020 1021 1022

;;; Debugging

1023 1024 1025 1026 1027
;;; Notice that SB-EXT:*INVOKE-DEBUGGER-HOOK* is slightly stronger
;;; than just a hook into BREAK. In particular, it'll make
;;; (LET ((*DEBUGGER-HOOK* NIL)) ..error..) drop into SLDB rather
;;; than the native debugger. That should probably be considered a
;;; feature.
1028

Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1029
(defun make-invoke-debugger-hook (hook)
1030 1031 1032 1033 1034 1035
  (when hook
    #'(sb-int:named-lambda swank-invoke-debugger-hook
          (condition old-hook)
        (if *debugger-hook*
            nil         ; decline, *DEBUGGER-HOOK* will be tried next.
            (funcall hook condition old-hook)))))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1036

1037 1038 1039 1040 1041 1042 1043
(defun set-break-hook (hook)
  (setq sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook)))

(defun call-with-break-hook (hook continuation)
  (let ((sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook)))
    (funcall continuation)))

1044
(defimplementation install-debugger-globally (function)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1045
  (setq *debugger-hook* function)
1046
  (set-break-hook function))
1047

Juho Snellman's avatar
Juho Snellman committed
1048
(defimplementation condition-extras (condition)
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
  (cond #+#.(swank-backend::sbcl-with-new-stepper-p)
        ((typep condition 'sb-impl::step-form-condition)
         `((:show-frame-source 0)))
        ((typep condition 'sb-int:reference-condition)
         (let ((refs (sb-int:reference-condition-references condition)))
           (if refs
               `((:references ,(externalize-reference refs))))))))

(defun externalize-reference (ref)
  (etypecase ref
    (null nil)
    (cons (cons (externalize-reference (car ref))
                (externalize-reference (cdr ref))))
    ((or string number) ref)
    (symbol 
     (cond ((eq (symbol-package ref) (symbol-package :test))
            ref)
           (t (symbol-name ref))))))
Juho Snellman's avatar
Juho Snellman committed
1067

1068 1069
(defvar *sldb-stack-top*)

1070
(defimplementation call-with-debugging-environment (debugger-loop-fn)
1071
  (declare (type function debugger-loop-fn))
1072 1073
  (let* ((*sldb-stack-top* (if *debug-swank-backend*
                               (sb-di:top-frame)
1074 1075
                               (or sb-debug:*stack-top-hint*
                                   (sb-di:top-frame))))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1076
         (sb-debug:*stack-top-hint* nil))
1077
    (handler-bind ((sb-di:debug-condition
1078
		    (lambda (condition)
1079 1080 1081 1082
                      (signal (make-condition
                               'sldb-condition
                               :original-condition condition)))))
      (funcall debugger-loop-fn))))
1083

Juho Snellman's avatar
Juho Snellman committed
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
#+#.(swank-backend::sbcl-with-new-stepper-p)
(progn
  (defimplementation activate-stepping (frame)
    (declare (ignore frame))
    (sb-impl::enable-stepping))
  (defimplementation sldb-stepper-condition-p (condition)
    (typep condition 'sb-ext:step-form-condition))
  (defimplementation sldb-step-into ()
    (invoke-restart 'sb-ext:step-into))
  (defimplementation sldb-step-next ()
    (invoke-restart 'sb-ext:step-next))
  (defimplementation sldb-step-out ()
    (invoke-restart 'sb-ext:step-out)))

1098
(defimplementation call-with-debugger-hook (hook fun)
1099 1100
  (let ((*debugger-hook* hook)
        #+#.(swank-backend::sbcl-with-new-stepper-p)
Juho Snellman's avatar
Juho Snellman committed
1101 1102
        (sb-ext:*stepper-hook*
         (lambda (condition)
1103 1104 1105 1106 1107 1108
           (typecase condition
             (sb-ext:step-form-condition
              (let ((sb-debug:*stack-top-hint* (sb-di::find-stepped-frame)))
                (sb-impl::invoke-debugger condition)))))))
    (handler-bind (#+#.(swank-backend::sbcl-with-new-stepper-p)
                   (sb-ext:step-condition #'sb-impl::invoke-stepper))
1109
      (call-with-break-hook hook fun))))
1110

1111 1112 1113 1114 1115
(defun nth-frame (index)
  (do ((frame *sldb-stack-top* (sb-di:frame-down frame))
       (i index (1- i)))
      ((zerop i) frame)))

1116
(defimplementation compute-backtrace (start end)
1117 1118 1119 1120
  "Return a list of frames starting with frame number START and
continuing to frame number END or, if END is nil, the last frame on the
stack."
  (let ((end (or end most-positive-fixnum)))
1121 1122
    (loop for f = (nth-frame start) then (sb-di:frame-down f)
	  for i from start below end
1123
	  while f collect f)))
1124

1125 1126
(defimplementation print-frame (frame stream)
  (sb-debug::print-frame-call frame stream))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1127

1128
(defimplementation frame-restartable-p (frame)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1129
  #+#.(swank-backend::sbcl-with-restart-frame)
1130
  (not (null (sb-debug:frame-has-debug-tag-p frame))))
1131

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
(defimplementation frame-call (frame-number)
  (multiple-value-bind (name args)
      (sb-debug::frame-call (nth-frame frame-number))
    (with-output-to-string (stream)
      (pprint-logical-block (stream nil :prefix "(" :suffix ")")
        (let ((*print-length* nil)
              (*print-level* nil))
          (prin1 (sb-debug::ensure-printable-object name) stream))
        (let ((args (sb-debug::ensure-printable-object args)))
          (if (listp args)
              (format stream "~{ ~_~S~}" args)
              (format stream " ~S" args)))))))

1145
;;;; Code-location -> source-location translation
1146

Helmut Eller's avatar
Helmut Eller committed
1147 1148 1149 1150 1151 1152
;;; If debug-block info is avaibale, we determine the file position of
;;; the source-path for a code-location.  If the code was compiled
;;; with C-c C-c, we have to search the position in the source string.
;;; If there's no debug-block info, we return the (less precise)
;;; source-location of the corresponding function.

1153 1154 1155 1156 1157
(defun code-location-source-location (code-location)
  (let* ((dsource (sb-di:code-location-debug-source code-location))
         (plist (sb-c::debug-source-plist dsource)))
    (if (getf plist :emacs-buffer)
        (emacs-buffer-source-location code-location plist)
1158
        #+#.(swank-backend:with-symbol 'debug-source-from 'sb-di)
1159 1160
        (ecase (sb-di:debug-source-from dsource)
          (:file (file-source-location code-location))
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1161
          (:lisp (lisp-source-location code-location)))
1162
        #-#.(swank-backend:with-symbol 'debug-source-from 'sb-di)
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1163 1164 1165
        (if (sb-di:debug-source-namestring dsource)
            (file-source-location code-location)
            (lisp-source-location code-location)))))
1166 1167 1168 1169 1170

;;; FIXME: The naming policy of source-location functions is a bit
;;; fuzzy: we have FUNCTION-SOURCE-LOCATION which returns the
;;; source-location for a function, and we also have FILE-SOURCE-LOCATION &co
;;; which returns the source location for a _code-location_.
1171
;;;
1172
;;; Maybe these should be named code-location-file-source-location,
1173 1174 1175
;;; etc, turned into generic functions, or something. In the very
;;; least the names should indicate the main entry point vs. helper
;;; status.
1176

1177 1178 1179 1180 1181 1182 1183 1184
(defun file-source-location (code-location)
  (if (code-location-has-debug-block-info-p code-location)
      (source-file-source-location code-location)
      (fallback-source-location code-location)))

(defun fallback-source-location (code-location)
  (let ((fun (code-location-debug-fun-fun code-location)))
    (cond (fun (function-source-location fun))
1185
          (t (error "Cannot find source location for: ~A " code-location)))))
1186

1187
(defun lisp-source-location (code-location)
1188
  (let ((source (prin1-to-string
1189
                 (sb-debug::code-location-source-form code-location 100)))
1190
        (condition (swank-value '*swank-debugger-condition*)))
1191 1192
    (if (and (typep condition 'sb-impl::step-form-condition)
             (search "SB-IMPL::WITH-STEPPING-ENABLED" source
1193 1194
                     :test #'char-equal)
             (search "SB-IMPL::STEP-FINISHED" source :test #'char-equal))
1195 1196
        ;; The initial form is utterly uninteresting -- and almost
        ;; certainly right there in the REPL.
1197 1198
        (make-error-location "Stepping...")
        (make-location `(:source-form ,source) '(:position 1)))))
1199

1200 1201
(defun emacs-buffer-source-location (code-location plist)
  (if (code-location-has-debug-block-info-p code-location)
1202 1203 1204
      (destructuring-bind (&key emacs-buffer emacs-position emacs-string
                                &allow-other-keys)
          plist
1205
        (let* ((pos (string-source-position code-location emacs-string))
1206
               (snipped (read-snippet-from-string emacs-string pos)))
1207
          (make-location `(:buffer ,emacs-buffer)
1208
                         `(:offset ,emacs-position ,pos)
1209 1210 1211
                         `(:snippet ,snipped))))
      (fallback-source-location code-location)))

1212 1213 1214
(defun source-file-source-location (code-location)
  (let* ((code-date (code-location-debug-source-created code-location))
         (filename (code-location-debug-source-name code-location))
1215
         (*readtable* (guess-readtable-for-filename filename))
1216
         (source-code (get-source-code filename code-date)))
1217 1218 1219 1220 1221
    (with-debootstrapping
      (with-input-from-string (s source-code)
        (let* ((pos (stream-source-position code-location s))
               (snippet (read-snippet s pos)))
          (make-location `(:file ,filename)
1222
                         `(:position ,pos)
1223
                         `(:snippet ,snippet)))))))
1224 1225

(defun code-location-debug-source-name (code-location)
1226
  (namestring (truename (#+#.(swank-backend:with-symbol
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1227 1228
                              'debug-source-name 'sb-di)
                             sb-c::debug-source-name
1229
                             #-#.(swank-backend:with-symbol
Tobias C. Rittweiler's avatar
Tobias C. Rittweiler committed
1230 1231
                                  'debug-source-name 'sb-di)
                             sb-c::debug-source-namestring
1232
                         (sb-di::code-location-debug-source code-location)))))
1233 1234

(defun code-location-debug-source-created (code-location)
1235
  (sb-c::debug-source-created
1236 1237 1238 1239 1240 1241
   (sb-di::code-location-debug-source code-location)))

(defun code-location-debug-fun-fun (code-location)
  (sb-di:debug-fun-fun (sb-di:code-location-debug-fun code-location)))

(defun code-location-has-debug-block-info-p (code-location)
1242
  (handler-case
1243 1244 1245 1246 1247 1248
      (progn (sb-di:code-location-debug-block code-location)
             t)
    (sb-di:no-debug-blocks  () nil)))

(defun stream-source-position (code-location stream)
  (let* ((cloc (sb-debug::maybe-block-start-location code-location))
1249
	 (tlf-number (sb-di::code-location-toplevel-form-offset cloc))
1250 1251 1252
	 (form-number (sb-di::code-location-form-number cloc)))
    (multiple-value-bind (tlf pos-map) (read-source-form tlf-number stream)
      (let* ((path-table (sb-di::form-number-translations tlf 0))
1253
             (path (cond ((<= (length path-table) form-number)
Helmut Eller's avatar
Helmut Eller committed
1254
                          (warn "inconsistent form-number-translations")
1255 1256 1257 1258 1259 1260 1261 1262
                          (list 0))
                         (t
                          (reverse (cdr (aref path-table form-number)))))))
        (source-path-source-position path tlf pos-map)))))

(defun string-source-position (code-location string)
  (with-input-from-string (s string)
    (stream-source-position code-location s)))
1263

1264
;;; source-path-file-position and friends are in swank-source-path-parser
1265

1266
(defimplementation frame-source-location (index)
1267
  (converting-errors-to-error-location
1268 1269
    (code-location-source-location
     (sb-di:frame-code-location (nth-frame index)))))
1270

1271 1272 1273 1274 1275 1276 1277 1278 1279
(defun frame-debug-vars (frame)
  "Return a vector of debug-variables in frame."
  (sb-di::debug-fun-debug-vars (sb-di:frame-debug-fun frame)))

(defun debug-var-value (var frame location)
  (ecase (sb-di:debug-var-validity var location)
    (:valid (sb-di:debug-var-value var frame))
    ((:invalid :unknown) ':<not-available>)))

1280 1281 1282 1283 1284 1285
(defun debug-var-info (var)
  ;; Introduced by SBCL 1.0.49.76.
  (let ((s (find-symbol "DEBUG-VAR-INFO" :sb-di)))
    (when (and s (fboundp s))
      (funcall s var))))

1286
(defimplementation frame-locals (index)
1287
  (let* ((frame (nth-frame index))
1288
	 (loc (sb-di:frame-code-location frame))
1289 1290 1291 1292 1293 1294 1295
	 (vars (frame-debug-vars frame))
         ;; Since SBCL 1.0.49.76 PREPROCESS-FOR-EVAL understands SB-DEBUG::MORE
         ;; specially.
         (more-name (or (find-symbol "MORE" :sb-debug) 'more))
         (more-context nil)
         (more-count nil)
         (more-id 0))
1296
    (when vars
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
      (let ((locals
              (loop for v across vars
                    do (when (eq (sb-di:debug-var-symbol v) more-name)
                         (incf more-id))
                       (case (debug-var-info v)
                         (:more-context
                          (setf more-context (debug-var-value v frame loc)))
                         (:more-count
                          (setf more-count (debug-var-value v frame loc))))
                    collect
                       (list :name (sb-di:debug-var-symbol v)
                             :id (sb-di:debug-var-id v)
                             :value (debug-var-value v frame loc)))))
        (when (and more-context more-count)
          (setf locals (append locals
                               (list
                                (list :name more-name
                                      :id more-id
                                      :value (multiple-value-list
1316 1317 1318
                                              (sb-c:%more-arg-values 
                                               more-context
                                               0 more-count)))))))
1319
        locals))))
1320 1321 1322

(defimplementation frame-var-value (frame var)
  (let* ((frame (nth-frame frame))
1323 1324 1325
         (vars (frame-debug-vars frame))
         (loc (sb-di:frame-code-location frame))
         (dvar (if (= var (length vars))
1326 1327 1328 1329 1330 1331 1332 1333
                   ;; If VAR is out of bounds, it must be the fake var
                   ;; we made up for &MORE.
                   (let* ((context-var (find :more-context vars 
                                             :key #'debug-var-info))
                          (more-context (debug-var-value context-var frame 
                                                         loc))
                          (count-var (find :more-count vars 
                                           :key #'debug-var-info))
1334 1335
                          (more-count (debug-var-value count-var frame loc)))
                     (return-from frame-var-value
1336 1337 1338
                       (multiple-value-list (sb-c:%more-arg-values
                                             more-context
                                             0 more-count))))
1339 1340
                   (aref vars var))))
    (debug-var-value dvar frame loc)))
1341

1342
(defimplementation frame-catch-tags (index)
1343
  (mapcar #'car (sb-di:frame-catches (nth-frame index))))
1344

1345 1346
(defimplementation eval-in-frame (form index)
  (let ((frame (nth-frame index)))
1347
    (funcall (the function
1348
               (sb-di:preprocess-for-eval form