7059ffc04793c997ec6284da3965887ad8763628
[sbcl.git] / contrib / sb-aclrepl / repl.lisp
1 ;;;; Replicate much of the ACL toplevel functionality in SBCL. Mostly
2 ;;;; this is portable code, but fundamentally it all hangs from a few
3 ;;;; SBCL-specific hooks like SB-INT:*REPL-READ-FUN* and
4 ;;;; SB-INT:*REPL-PROMPT-FUN*.
5 ;;;;
6 ;;;; The documentation, which may or may not apply in its entirety at
7 ;;;; any given time, for this functionality is on the ACL website:
8 ;;;;   <http://www.franz.com/support/documentation/6.2/doc/top-level.htm>.
9
10 (cl:defpackage :sb-aclrepl
11   (:use :cl :sb-ext)
12   (:export #:*prompt* #:*exit-on-eof* #:*max-history*
13            #:*use-short-package-name* #:*command-char*
14            #:alias))
15
16 (cl:in-package :sb-aclrepl)
17
18 (defstruct user-cmd
19   (input nil) ; input, maybe a string or form
20   (func nil)  ; cmd func entered, overloaded
21               ; (:eof :null-cmd :cmd-error :history-error)
22   (args nil)  ; args for cmd func
23   (hnum nil)) ; history number
24
25 (defstruct break-data
26   ;; numeric break level
27   level
28   ;; inspect data for a break level
29   inspect
30   ;; T when break initiated by an inspect
31   inspect-initiated
32   ;; restarts list for a break level
33   restarts 
34   ;; T if break level is a continuable break
35   continuable) 
36
37 ;;; cmd table entry
38 (defstruct cmd-table-entry
39   (name nil) ; name of command
40   (func nil) ; function handler
41   (desc nil) ; short description
42   (parsing nil) ; (:string :case-sensitive nil)
43   (group nil) ; command group (:cmd or :alias)
44   (abbr-len 0)) ; abbreviation length
45   
46 (eval-when (:compile-toplevel :load-toplevel :execute)
47   (defparameter *default-prompt* "~:[~2*~;[~:*~D~:[~;i~]~:[~;c~]] ~]~A(~D): "
48     "The default prompt."))
49 (defparameter *prompt* #.*default-prompt*
50   "The current prompt string or formatter function.")
51 (defparameter *use-short-package-name* t
52   "when T, use the shortnest package nickname in a prompt")
53 (defparameter *dir-stack* nil
54   "The top-level directory stack")
55 (defparameter *command-char* #\:
56   "Prefix character for a top-level command")
57 (defvar *max-history* 24
58   "Maximum number of history commands to remember")
59 (defvar *exit-on-eof* t
60   "If T, then exit when the EOF character is entered.")
61 (defparameter *history* nil
62   "History list")
63 (defparameter *cmd-number* 1
64   "Number of the next command")
65 (defparameter *repl-output* nil
66   "The output stream for the repl")
67 (defparameter *repl-input* nil
68   "The input stream for the repl")
69 (defparameter *break-stack*  (list (make-break-data :level 0))
70   "A stack of break data stored as a list of break-level structs")
71
72 (declaim (type list *history*))
73
74 (defvar *eof-marker* :eof)
75 (defvar *eof-cmd* (make-user-cmd :func :eof))
76 (defvar *null-cmd* (make-user-cmd :func :null-cmd))
77
78 (defparameter *cmd-table-hash*
79   (make-hash-table :size 30 :test #'equal))
80
81 ;; Set up binding for multithreading
82
83 (let ((*prompt* #.*default-prompt*)
84       (*use-short-package-name* t)
85       (*dir-stack* nil)
86       (*command-char* #\:)
87       (*max-history* 24)
88       (*exit-on-eof* t)
89       (*history* nil)
90       (*cmd-number* 1)
91       (*repl-output* nil)
92       (*repl-input* nil)
93       (*break-stack* (list (make-break-data :level 0)))
94       )
95       
96 (defun prompt-package-name ()
97   (if *use-short-package-name*
98       (car (sort (append
99                   (package-nicknames cl:*package*)
100                   (list (package-name cl:*package*)))
101                  (lambda (a b) (< (length a) (length b)))))
102       (package-name cl:*package*)))
103
104 (defun read-cmd (input-stream)
105   ;; Reads a command from the user and returns a user-cmd object
106   (flet ((parse-args (parsing args-string)
107            (case parsing
108              (:string
109               (if (zerop (length args-string))
110                   nil
111                   (list args-string)))
112              (t
113               (let ((string-stream (make-string-input-stream args-string))
114                     (eof (cons nil *eof-marker*))) ;new cons for eq uniqueness
115                 (loop as arg = (read string-stream nil eof)
116                       until (eq arg eof)
117                       collect arg))))))
118     (let ((next-char (peek-char-non-whitespace input-stream)))
119       (cond
120         ((eql next-char *command-char*)
121          (let* ((line (string-trim-whitespace (read-line input-stream)))
122                 (first-space-pos (position #\space line))
123                 (cmd-string (subseq line 1 first-space-pos))
124                 (cmd-args-string
125                  (if first-space-pos
126                      (string-trim-whitespace (subseq line first-space-pos))
127                      "")))
128            (declare (string line))
129            (if (numberp (read-from-string cmd-string))
130                (let ((cmd (get-history (read-from-string cmd-string))))
131                  (if (eq cmd *null-cmd*)
132                      (make-user-cmd :func :history-error
133                                     :input (read-from-string cmd-string))
134                      (make-user-cmd :func (user-cmd-func cmd)
135                                     :input (user-cmd-input cmd)
136                                     :args (user-cmd-args cmd)
137                                     :hnum *cmd-number*)))
138                (let ((cmd-entry (find-cmd cmd-string)))
139                  (if cmd-entry
140                      (make-user-cmd :func (cmd-table-entry-func cmd-entry)
141                                     :input line
142                                     :args (parse-args
143                                            (cmd-table-entry-parsing cmd-entry)
144                                            cmd-args-string)
145                                     :hnum *cmd-number*)
146                      (make-user-cmd :func :cmd-error
147                                     :input cmd-string)
148                      )))))
149         ((eql next-char #\newline)
150          (read-char input-stream)
151          *null-cmd*)
152       (t
153        (let* ((eof (cons nil *eof-marker*))
154               (form (read input-stream nil eof)))
155          (if (eq form eof)
156              *eof-cmd*
157              (make-user-cmd :input form :func nil :hnum *cmd-number*))))))))
158
159 (defun make-cte (name-param func desc parsing group abbr-len)
160   (let ((name (etypecase name-param
161                 (string
162                  name-param)
163                 (symbol
164                  (string-downcase (write-to-string name-param))))))
165     (make-cmd-table-entry :name name :func func :desc desc
166                           :parsing parsing :group group
167                           :abbr-len (if abbr-len
168                                         abbr-len
169                                         (length name)))))
170
171 (defun %add-entry (cmd &optional abbr-len)
172   (let* ((name (cmd-table-entry-name cmd))
173          (alen (if abbr-len
174                    abbr-len
175                    (length name))))
176     (dotimes (i (length name))
177       (when (>= i (1- alen))
178         (setf (gethash (subseq name 0 (1+ i)) *cmd-table-hash*)
179               cmd)))))
180
181 (defun add-cmd-table-entry (cmd-string abbr-len func-name desc parsing)
182   (%add-entry
183    (make-cte cmd-string (symbol-function func-name) desc parsing :cmd abbr-len)
184    abbr-len))
185    
186 (defun find-cmd (cmdstr)
187   (gethash (string-downcase cmdstr) *cmd-table-hash*))
188
189 (defun user-cmd= (c1 c2)
190   "Returns T if two user commands are equal"
191   (and (eq (user-cmd-func c1) (user-cmd-func c2))
192        (equal (user-cmd-args c1) (user-cmd-args c2))
193        (equal (user-cmd-input c1) (user-cmd-input c2))))
194
195 (defun add-to-history (cmd)
196   (unless (and *history* (user-cmd= cmd (car *history*)))
197     (when (>= (length *history*) *max-history*)
198       (setq *history* (nbutlast *history* (+ (length *history*) *max-history* 1))))
199     (push cmd *history*)
200     (incf *cmd-number*)))
201
202 (defun get-history (n)
203   (let ((cmd (find n *history* :key #'user-cmd-hnum :test #'eql)))
204     (if cmd
205         cmd
206         *null-cmd*)))
207
208 (defun get-cmd-doc-list (&optional (group :cmd))
209   "Return list of all commands"
210   (let ((cmds '()))
211     (maphash (lambda (k v)
212                (when (and
213                       (= (length k) (length (cmd-table-entry-name v)))
214                       (eq (cmd-table-entry-group v) group))
215                  (push (list k
216                              (if (= (cmd-table-entry-abbr-len v)
217                                     (length k))
218                                   ""
219                                   (subseq k 0 (cmd-table-entry-abbr-len v)))
220                              (cmd-table-entry-desc v)) cmds)))
221              *cmd-table-hash*)
222     (sort cmds #'string-lessp :key #'car)))
223
224 (defun cd-cmd (&optional string-dir)
225   (cond
226     ((or (zerop (length string-dir))
227          (string= string-dir "~"))
228      (setf cl:*default-pathname-defaults* (user-homedir-pathname)))
229     (t
230      (let ((new (truename string-dir)))
231        (when (pathnamep new)
232          (setf cl:*default-pathname-defaults* new)))))
233   (format *repl-output* "~A~%" (namestring cl:*default-pathname-defaults*))
234   (values))
235
236 (defun pwd-cmd ()
237   (format *repl-output* "Lisp's current working directory is ~s.~%"
238           (namestring cl:*default-pathname-defaults*))
239   (values))
240
241 (defun trace-cmd (&rest args)
242   (if args
243       (format *repl-output* "~A~%" (eval (sb-debug::expand-trace args)))
244       (format *repl-output* "~A~%" (sb-debug::%list-traced-funs)))
245   (values))
246
247 (defun untrace-cmd (&rest args)
248   (if args
249       (format *repl-output* "~A~%"
250               (eval
251                (sb-int:collect ((res))
252                 (let ((current args))
253                   (loop
254                    (unless current (return))
255                    (let ((name (pop current)))
256                      (res (if (eq name :function)
257                               `(sb-debug::untrace-1 ,(pop current))
258                               `(sb-debug::untrace-1 ',name))))))
259                 `(progn ,@(res) t))))
260       (format *repl-output* "~A~%" (eval (sb-debug::untrace-all))))
261   (values))
262
263 #+sb-thread
264 (defun thread-pids ()
265   "Return a list of the pids for all threads"
266   (let ((offset (* 4 sb-vm::thread-pid-slot)))
267     (sb-thread::mapcar-threads
268      #'(lambda (sap) (sb-sys:sap-ref-32 sap offset)))))
269
270 #+sb-thread
271 (defun other-thread-pids ()
272   "Returns a list of pids for all threads except the current process"
273   (delete (sb-thread:current-thread-id) (thread-pids) :test #'eql))
274
275 (defun exit-cmd (&optional (status 0))
276   #+sb-thread
277   (let ((other-pids (other-thread-pids)))
278     (when other-pids
279       (format *repl-output* "There exists the following processes~%")
280       (format *repl-output* "~{~5d~%~}" other-pids)
281       (format *repl-output* "Do you want to exit lisp anyway [n]? ")
282       (force-output *repl-output*)
283       (let ((input (string-trim-whitespace (read-line *repl-input*))))
284         (if (and (plusp (length input))
285                  (or (char= #\y (char input 0))
286                      (char= #\Y (char input 0))))
287             ;; loop in case more threads get created while trying to exit
288             (do ((pids other-pids (other-thread-pids)))
289                 ((eq nil pids))
290               (map nil #'sb-thread:destroy-thread pids)
291               (sleep 0.2))
292             (return-from exit-cmd)))))
293   (quit :unix-status status)
294   (values))
295
296 (defun package-cmd (&optional pkg)
297   (cond
298     ((null pkg)
299      (format *repl-output* "The ~A package is current.~%"
300              (package-name cl:*package*)))
301     ((null (find-package (write-to-string pkg)))
302      (format *repl-output* "Unknown package: ~A.~%" pkg))
303     (t
304      (setf cl:*package* (find-package (write-to-string pkg)))))
305   (values))
306
307 (defun string-to-list-skip-spaces (str)
308   "Return a list of strings, delimited by spaces, skipping spaces."
309   (declare (string str)) 
310   (when str
311     (loop for i = 0 then (1+ j)
312           as j = (position #\space str :start i)
313           when (not (char= (char str i) #\space))
314           collect (subseq str i j) while j)))
315
316 (let ((last-files-loaded nil))
317   (defun ld-cmd (&optional string-files)
318     (if string-files
319         (setq last-files-loaded string-files)
320         (setq string-files last-files-loaded))
321     (dolist (arg (string-to-list-skip-spaces string-files))
322       (format *repl-output* "loading ~a~%" arg)
323       (load arg)))
324   (values))
325
326 (defun cf-cmd (string-files)
327   (when string-files
328     (dolist (arg (string-to-list-skip-spaces string-files))
329       (compile-file arg)))
330   (values))
331
332 (defun >-num (x y)
333   "Return if x and y are numbers, and x > y"
334   (and (numberp x) (numberp y) (> x y)))
335
336 (defun newer-file-p (file1 file2)
337   "Is file1 newer (written later than) file2?"
338   (>-num (if (probe-file file1) (file-write-date file1))
339          (if (probe-file file2) (file-write-date file2))))
340
341 (defun compile-file-as-needed (src-path)
342   "Compiles a file if needed, returns path."
343   (let ((dest-path (compile-file-pathname src-path)))
344     (when (or (not (probe-file dest-path))
345               (newer-file-p src-path dest-path))
346       (ensure-directories-exist dest-path)
347       (compile-file src-path :output-file dest-path))
348     dest-path))
349 \f
350 ;;;; implementation of commands
351
352 (defun apropos-cmd (string)
353   (apropos (string-upcase string))
354   (values))
355
356 (let ((last-files-loaded nil))
357   (defun cload-cmd (&optional string-files)
358     (if string-files
359         (setq last-files-loaded string-files)
360         (setq string-files last-files-loaded))
361     (dolist (arg (string-to-list-skip-spaces string-files))
362       (format *repl-output* "loading ~a~%" arg)
363       (load (compile-file-as-needed arg)))
364     (values)))
365
366 (defun inspect-cmd (arg)
367   (inspector arg nil *repl-output*)
368   (values))
369
370 (defun istep-cmd (&optional arg-string)
371   (istep arg-string *repl-output*)
372   (values))
373
374 (defun describe-cmd (&rest args)
375   (dolist (arg args)
376     (eval `(describe ,arg)))
377   (values))
378
379 (defun macroexpand-cmd (arg)
380   (pprint (macroexpand arg) *repl-output*)
381   (values))
382
383 (defun history-cmd ()
384   (let ((n (length *history*)))
385     (declare (fixnum n))
386     (dotimes (i n)
387       (declare (fixnum i))
388       (let ((hist (nth (- n i 1) *history*)))
389         (format *repl-output* "~3A " (user-cmd-hnum hist))
390         (if (stringp (user-cmd-input hist))
391             (format *repl-output* "~A~%" (user-cmd-input hist))
392             (format *repl-output* "~W~%" (user-cmd-input hist))))))
393   (values))
394
395 (defun help-cmd (&optional cmd)
396   (cond
397     (cmd
398      (let ((cmd-entry (find-cmd cmd)))
399        (if cmd-entry
400            (format *repl-output* "Documentation for ~A: ~A~%"
401                    (cmd-table-entry-name cmd-entry)
402                    (cmd-table-entry-desc cmd-entry)))))
403     (t
404      (format *repl-output* "~11A ~4A ~A~%" "COMMAND" "ABBR" "DESCRIPTION")
405      (format *repl-output* "~11A ~4A ~A~%" "<n>" ""
406              "re-execute <n>th history command")
407      (dolist (doc-entry (get-cmd-doc-list :cmd))
408        (format *repl-output* "~11A ~4A ~A~%" (first doc-entry)
409                (second doc-entry) (third doc-entry)))))
410   (values))
411
412 (defun alias-cmd ()
413   (let ((doc-entries (get-cmd-doc-list :alias)))
414     (typecase doc-entries
415       (cons
416        (format *repl-output* "~11A ~A ~4A~%" "ALIAS" "ABBR" "DESCRIPTION")
417        (dolist (doc-entry doc-entries)
418          (format *repl-output* "~11A ~4A ~A~%" (first doc-entry) (second doc-entry) (third doc-entry))))
419       (t
420        (format *repl-output* "No aliases are defined~%"))))
421   (values))
422
423 (defun shell-cmd (string-arg)
424   (sb-ext:run-program "/bin/sh" (list "-c" string-arg)
425                       :input nil :output *repl-output*)
426   (values))
427
428 (defun pushd-cmd (string-arg)
429   (push string-arg *dir-stack*)
430   (cd-cmd *repl-output* string-arg)
431   (values))
432
433 (defun popd-cmd ()
434   (if *dir-stack*
435       (let ((dir (pop *dir-stack*)))
436         (cd-cmd dir))
437       (format *repl-output* "No directory on stack to pop.~%"))
438   (values))
439
440 (defun pop-cmd (&optional (n 1))
441   (let ((new-level (- (length *break-stack*) n 1)))
442     (when (minusp new-level)
443       (setq new-level 0))
444     (dotimes (i (- (length *break-stack*) new-level 1))
445       (pop *break-stack*)))
446   ;; Find inspector 
447   (do* ((i (1- (length *break-stack*)) (1- i))
448         (found nil))
449        ((or found (minusp i)))
450     (let ((inspect (break-data-inspect (nth i *break-stack*))))
451       (when inspect
452         (set-current-inspect inspect)
453         (setq found t))))
454   (values))
455
456 (defun continue-cmd (n)
457   (let ((restarts (break-data-restarts (car *break-stack*))))
458     (if restarts
459         (if (< -1 n (length restarts))
460             (progn
461               (invoke-restart-interactively (nth n restarts))
462               )
463             (format *repl-output* "~&There is no such restart"))
464         (format *repl-output* "~&There are no restarts"))))
465
466 (defun error-cmd ()
467   )
468
469 (defun current-cmd ()
470   )
471
472 (defun frame-cmd ()
473   )
474
475 (defun zoom-cmd ()
476   )
477
478 (defun local-cmd (&optional var)
479   )
480
481 (defun processes-cmd ()
482   #+sb-thread
483   (let ((pids (thread-pids))
484         (current-pid (sb-thread:current-thread-id)))
485     (dolist (pid pids)
486       (format *repl-output* "~&~D" pid)
487       (when (= pid current-pid)
488         (format *repl-output* " [current listener]"))))
489   #-sb-thread
490   (format *repl-output* "~&Threads are not supported in this version of sbcl")
491   (values))
492
493 (defun kill-cmd (selected-pid)
494   #+sb-thread
495   (let ((pids (thread-pids)))
496     (if (find selected-pid pids :test #'eql)
497         (progn
498           (sb-thread:destroy-thread selected-pid)
499           (format *repl-output* "Thread ~D destroyed" selected-pid))
500         (format *repl-output* "No thread ~D exists" selected-pid)))
501   #-sb-thread
502   (declare (ignore selected-pid))
503   #-sb-thread
504   (format *repl-output* "~&Threads are not supported in this version of sbcl")
505   (values))
506
507 (defun reset-cmd ()
508   (setf *break-stack* (last *break-stack*))
509   (values))
510
511 (defun dirs-cmd ()
512   (dolist (dir *dir-stack*)
513     (format *repl-output* "~a~%" dir))
514   (values))
515
516 \f
517 ;;;; dispatch table for commands
518
519 (let ((cmd-table
520        '(("aliases" 3 alias-cmd "show aliases")
521          ("apropos" 2 apropos-cmd "show apropos" :parsing :string)
522          ("cd" 2 cd-cmd "change default diretory" :parsing :string)
523          ("ld" 2 ld-cmd "load a file" :parsing :string)
524          ("cf" 2 cf-cmd "compile file" :parsing :string)
525          ("cload" 2 cload-cmd "compile if needed and load file"
526           :parsing :string)
527          #+aclrepl-debugger("current" 3 current-cmd "print the expression for the current stack frame")
528          #+aclrepl-debugger ("continue" 4 continue-cmd "continue from a continuable error")
529          ("describe" 2 describe-cmd "describe an object")
530          ("macroexpand" 2 macroexpand-cmd "macroexpand an expression")
531          ("package" 2 package-cmd "change current package")
532          #+aclrepl-debugger ("error" 3 error-cmd "print the last error message")
533          ("exit" 2 exit-cmd "exit sbcl")
534          #+aclrepl-debugger("frame" 2 frame-cmd "print info about the current frame")
535          ("help" 2 help-cmd "print this help")
536          ("history" 3 history-cmd "print the recent history")
537          ("inspect" 2 inspect-cmd "inspect an object")
538          ("istep" 1 istep-cmd "navigate within inspection of a lisp object" :parsing :string)
539          #+sb-thread ("kill" 2 kill-cmd "kill a process")
540          #+aclrepl-debugger("local" 3 local-cmd "print the value of a local variable")
541          ("pwd" 3 pwd-cmd "print current directory")
542          ("pushd" 2 pushd-cmd "push directory on stack" :parsing :string)
543          ("pop" 3 pop-cmd "pop up `n' (default 1) break levels")
544          ("popd" 4 popd-cmd "pop directory from stack")
545          #+sb-thread ("processes" 3 processes-cmd "list all processes")
546          ("trace" 2 trace-cmd "trace a function")
547          ("untrace" 4 untrace-cmd "untrace a function")
548          ("dirs" 2 dirs-cmd "show directory stack")
549          ("shell" 2 shell-cmd "execute a shell cmd" :parsing :string)
550          #+aclrepl-debugger ("zoom" 2 zoom-cmd "print the runtime stack")
551          )))
552   (dolist (cmd cmd-table)
553     (destructuring-bind (cmd-string abbr-len func-name desc &key parsing) cmd
554       (add-cmd-table-entry cmd-string abbr-len func-name desc parsing))))
555 \f
556 ;;;; machinery for aliases
557
558 (defsetf alias (name &key abbr-len description) (user-func)
559   `(progn
560     (%add-entry
561      (make-cte (quote ,name) ,user-func ,description nil :alias ,abbr-len))
562     (quote ,name)))
563
564 (defmacro alias (name-param args &rest body)
565   (let ((parsing nil)
566         (desc "")
567         (abbr-index nil)
568         (name (if (atom name-param)
569                   name-param
570                   (car name-param))))
571     (when (consp name-param)
572      (dolist (param (cdr name-param))
573         (cond
574           ((or
575             (eq param :case-sensitive)
576             (eq param :string))
577            (setq parsing param))
578           ((stringp param)
579            (setq desc param))
580           ((numberp param)
581            (setq abbr-index param)))))
582     `(progn
583       (%add-entry
584        (make-cte (quote ,name) (lambda ,args ,@body) ,desc ,parsing :alias (when ,abbr-index
585                                                                                (1+ ,abbr-index)))
586        ,abbr-index)
587       ,name)))
588        
589     
590 (defun remove-alias (&rest aliases)
591   (declare (list aliases))
592   (let ((keys '())
593         (remove-all (not (null (find :all aliases)))))
594     (unless remove-all  ;; ensure all alias are strings
595       (setq aliases
596             (loop for alias in aliases
597                   collect
598                   (etypecase alias
599                     (string
600                      alias)
601                     (symbol
602                      (symbol-name alias))))))
603     (maphash
604      (lambda (key cmd)
605        (when (eq (cmd-table-entry-group cmd) :alias)
606          (if remove-all
607              (push key keys)
608              (when (some
609                     (lambda (alias)
610                       (let ((klen (length key)))
611                         (and (>= (length alias) klen)
612                              (string-equal (subseq alias 0 klen)
613                                            (subseq key 0 klen)))))
614                     aliases)
615                (push key keys)))))
616      *cmd-table-hash*)
617     (dolist (key keys)
618       (remhash key *cmd-table-hash*))
619     keys))
620 \f
621 ;;;; low-level reading/parsing functions
622
623 ;;; Skip white space (but not #\NEWLINE), and peek at the next
624 ;;; character.
625 (defun peek-char-non-whitespace (&optional stream)
626   (do ((char (peek-char nil stream nil *eof-marker*)
627              (peek-char nil stream nil *eof-marker*)))
628       ((not (whitespace-char-not-newline-p char)) char)
629     (read-char stream)))
630
631 (defun string-trim-whitespace (str)
632   (string-trim '(#\space #\tab #\return)
633                str))
634
635 (defun whitespace-char-not-newline-p (x)
636   (and (characterp x)
637        (or (char= x #\space)
638            (char= x #\tab)
639            (char= x #\return))))
640
641 \f
642 ;;;; linking into SBCL hooks
643
644 (defun repl-prompt-fun (stream)
645   (let* ((break-data (car *break-stack*))
646          (break-level (break-data-level break-data)))
647     (when (zerop break-level)
648       (setq break-level nil))
649     (if (functionp *prompt*)
650         (write-string (funcall *prompt* break-level
651                                (break-data-inspect-initiated break-data)
652                                (break-data-continuable break-data)
653                                (prompt-package-name) *cmd-number*)
654                       stream)
655         (handler-case 
656             (format nil *prompt* break-level
657                     (break-data-inspect-initiated break-data)
658                     (break-data-continuable break-data)
659                     (prompt-package-name) *cmd-number*)
660           (error ()
661             (format stream "~&Prompt error>  "))
662           (:no-error (prompt)
663             (format stream "~&~A" prompt))))))
664   
665 (defun process-cmd (user-cmd input-stream output-stream)
666   ;; Processes a user command. Returns t if the user-cmd was a top-level
667   ;; command
668   (cond ((eq user-cmd *eof-cmd*)
669          (when *exit-on-eof*
670            (quit))
671          (format output-stream "EOF~%")
672          t)
673         ((eq user-cmd *null-cmd*)
674          t)
675         ((eq (user-cmd-func user-cmd) :cmd-error)
676          (format output-stream "Unknown top-level command: ~s.~%"
677                  (user-cmd-input user-cmd))
678          (format output-stream "Type `:help' for the list of commands.~%")
679          t)
680         ((eq (user-cmd-func user-cmd) :history-error)
681          (format output-stream "Input numbered ~d is not on the history list~%"
682                  (user-cmd-input user-cmd))
683          t)
684         ((functionp (user-cmd-func user-cmd))
685          (add-to-history user-cmd)
686          (let ((*repl-output* output-stream)
687                (*repl-input* input-stream))
688            (apply (user-cmd-func user-cmd) (user-cmd-args user-cmd)))
689          (fresh-line)
690          t)
691         (t
692          (add-to-history user-cmd)
693          nil))) ; nope, not in my job description
694
695 (defun repl-read-form-fun (input-stream output-stream)
696   ;; Pick off all the leading ACL magic commands, then return a normal
697   ;; Lisp form.
698   (loop for user-cmd = (read-cmd input-stream) do
699         (if (process-cmd user-cmd input-stream output-stream)
700             (progn
701               (funcall sb-int:*repl-prompt-fun* output-stream)
702               (force-output output-stream))
703             (return (user-cmd-input user-cmd)))))
704
705
706 (setf sb-int:*repl-prompt-fun* #'repl-prompt-fun
707       sb-int:*repl-read-form-fun* #'repl-read-form-fun)
708
709 ;;; Break level processing
710
711 ;; use an initial break-level to hold current inspect toplevel at
712 ;; break-level 0
713
714 (defun new-break (&key restarts inspect continuable)
715   (push
716    (make-break-data :level (length *break-stack*)
717                     :restarts restarts
718                     :inspect inspect
719                     :inspect-initiated (when inspect t)
720                     :continuable continuable)
721    *break-stack*))
722
723 (defun set-break-inspect (inspect)
724   "sets the inspect data for the current break level"
725   (setf (break-data-inspect (car *break-stack*)) inspect))
726
727 ) ;; close special variables bindings
728