fe2237554dc2b7e55829fbf36c9c49896c392ff6
[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 (&rest selected-pids)
494   #+sb-thread
495   (let ((pids (thread-pids)))
496     (dolist (selected-pid selected-pids) 
497       (if (find selected-pid pids :test #'eql)
498           (progn
499             (sb-thread:destroy-thread selected-pid)
500             (format *repl-output* "~&Thread ~A destroyed" selected-pid))
501           (format *repl-output* "~&No thread ~A exists" selected-pid))))
502   #-sb-thread
503   (declare (ignore selected-pids))
504   #-sb-thread
505   (format *repl-output* "~&Threads are not supported in this version of sbcl")
506   (values))
507
508 (defun signal-cmd (signal &rest selected-pids)
509   #+sb-thread
510   (let ((pids (thread-pids)))
511     (dolist (selected-pid selected-pids)
512       (if (find selected-pid pids :test #'eql)
513           (progn
514             (sb-unix:unix-kill selected-pid signal)
515             (format *repl-output* "~&Signal ~A sent to thread ~A"
516                     signal selected-pid))
517           (format *repl-output* "~&No thread ~A exists" selected-pid))))
518   #-sb-thread
519   (declare (ignore selected-pids))
520   #-sb-thread
521   (format *repl-output* "~&Threads are not supported in this version of sbcl")
522   (values))
523
524 (defun release-foreground-cmd ()
525   #+sb-thread
526   (progn
527     (sb-thread:release-foreground)
528     (sleep 1))
529   #-sb-thread
530   #-sb-thread
531   (format *repl-output* "~&Threads are not supported in this version of sbcl")
532   (values))
533
534 (defun reset-cmd ()
535   (setf *break-stack* (last *break-stack*))
536   (values))
537
538 (defun dirs-cmd ()
539   (dolist (dir *dir-stack*)
540     (format *repl-output* "~a~%" dir))
541   (values))
542
543 \f
544 ;;;; dispatch table for commands
545
546 (let ((cmd-table
547        '(("aliases" 3 alias-cmd "show aliases")
548          ("apropos" 2 apropos-cmd "show apropos" :parsing :string)
549          ("cd" 2 cd-cmd "change default diretory" :parsing :string)
550          ("ld" 2 ld-cmd "load a file" :parsing :string)
551          ("cf" 2 cf-cmd "compile file" :parsing :string)
552          ("cload" 2 cload-cmd "compile if needed and load file"
553           :parsing :string)
554          #+aclrepl-debugger("current" 3 current-cmd "print the expression for the current stack frame")
555          #+aclrepl-debugger ("continue" 4 continue-cmd "continue from a continuable error")
556          ("describe" 2 describe-cmd "describe an object")
557          ("macroexpand" 2 macroexpand-cmd "macroexpand an expression")
558          ("package" 2 package-cmd "change current package")
559          #+aclrepl-debugger ("error" 3 error-cmd "print the last error message")
560          ("exit" 2 exit-cmd "exit sbcl")
561          #+aclrepl-debugger("frame" 2 frame-cmd "print info about the current frame")
562          ("help" 2 help-cmd "print this help")
563          ("history" 3 history-cmd "print the recent history")
564          ("inspect" 2 inspect-cmd "inspect an object")
565          ("istep" 1 istep-cmd "navigate within inspection of a lisp object" :parsing :string)
566          #+sb-thread ("kill" 2 kill-cmd "kill (destroy) processes")
567          #+sb-thread ("signal" 2 signal-cmd "send a signal to processes")
568          #+sb-thread ("rf" 2 release-foreground-cmd "release foreground")
569          #+aclrepl-debugger("local" 3 local-cmd "print the value of a local variable")
570          ("pwd" 3 pwd-cmd "print current directory")
571          ("pushd" 2 pushd-cmd "push directory on stack" :parsing :string)
572          ("pop" 3 pop-cmd "pop up `n' (default 1) break levels")
573          ("popd" 4 popd-cmd "pop directory from stack")
574          #+sb-thread ("processes" 3 processes-cmd "list all processes")
575          ("trace" 2 trace-cmd "trace a function")
576          ("untrace" 4 untrace-cmd "untrace a function")
577          ("dirs" 2 dirs-cmd "show directory stack")
578          ("shell" 2 shell-cmd "execute a shell cmd" :parsing :string)
579          #+aclrepl-debugger ("zoom" 2 zoom-cmd "print the runtime stack")
580          )))
581   (dolist (cmd cmd-table)
582     (destructuring-bind (cmd-string abbr-len func-name desc &key parsing) cmd
583       (add-cmd-table-entry cmd-string abbr-len func-name desc parsing))))
584 \f
585 ;;;; machinery for aliases
586
587 (defsetf alias (name &key abbr-len description) (user-func)
588   `(progn
589     (%add-entry
590      (make-cte (quote ,name) ,user-func ,description nil :alias ,abbr-len))
591     (quote ,name)))
592
593 (defmacro alias (name-param args &rest body)
594   (let ((parsing nil)
595         (desc "")
596         (abbr-index nil)
597         (name (if (atom name-param)
598                   name-param
599                   (car name-param))))
600     (when (consp name-param)
601      (dolist (param (cdr name-param))
602         (cond
603           ((or
604             (eq param :case-sensitive)
605             (eq param :string))
606            (setq parsing param))
607           ((stringp param)
608            (setq desc param))
609           ((numberp param)
610            (setq abbr-index param)))))
611     `(progn
612       (%add-entry
613        (make-cte (quote ,name) (lambda ,args ,@body) ,desc ,parsing :alias (when ,abbr-index
614                                                                                (1+ ,abbr-index)))
615        ,abbr-index)
616       ,name)))
617        
618     
619 (defun remove-alias (&rest aliases)
620   (declare (list aliases))
621   (let ((keys '())
622         (remove-all (not (null (find :all aliases)))))
623     (unless remove-all  ;; ensure all alias are strings
624       (setq aliases
625             (loop for alias in aliases
626                   collect
627                   (etypecase alias
628                     (string
629                      alias)
630                     (symbol
631                      (symbol-name alias))))))
632     (maphash
633      (lambda (key cmd)
634        (when (eq (cmd-table-entry-group cmd) :alias)
635          (if remove-all
636              (push key keys)
637              (when (some
638                     (lambda (alias)
639                       (let ((klen (length key)))
640                         (and (>= (length alias) klen)
641                              (string-equal (subseq alias 0 klen)
642                                            (subseq key 0 klen)))))
643                     aliases)
644                (push key keys)))))
645      *cmd-table-hash*)
646     (dolist (key keys)
647       (remhash key *cmd-table-hash*))
648     keys))
649 \f
650 ;;;; low-level reading/parsing functions
651
652 ;;; Skip white space (but not #\NEWLINE), and peek at the next
653 ;;; character.
654 (defun peek-char-non-whitespace (&optional stream)
655   (do ((char (peek-char nil stream nil *eof-marker*)
656              (peek-char nil stream nil *eof-marker*)))
657       ((not (whitespace-char-not-newline-p char)) char)
658     (read-char stream)))
659
660 (defun string-trim-whitespace (str)
661   (string-trim '(#\space #\tab #\return)
662                str))
663
664 (defun whitespace-char-not-newline-p (x)
665   (and (characterp x)
666        (or (char= x #\space)
667            (char= x #\tab)
668            (char= x #\return))))
669
670 \f
671 ;;;; linking into SBCL hooks
672
673
674 (defun repl-prompt-fun (stream)
675   (let* ((break-data (car *break-stack*))
676          (break-level (break-data-level break-data)))
677     (when (zerop break-level)
678       (setq break-level nil))
679     #+sb-thread
680     (let ((lock sb-thread::*session-lock*))
681       (sb-thread::get-foreground)
682       (let ((stopped-threads (sb-thread::waitqueue-data lock)))
683         (when stopped-threads
684           (format stream "~{~&Thread ~A suspended~}~%" stopped-threads))))
685     (if (functionp *prompt*)
686         (write-string (funcall *prompt* break-level
687                                (break-data-inspect-initiated break-data)
688                                (break-data-continuable break-data)
689                                (prompt-package-name) *cmd-number*)
690                       stream)
691         (handler-case 
692             (format nil *prompt* break-level
693                     (break-data-inspect-initiated break-data)
694                     (break-data-continuable break-data)
695                     (prompt-package-name) *cmd-number*)
696           (error ()
697             (format stream "~&Prompt error>  "))
698           (:no-error (prompt)
699             (format stream "~&~A" prompt))))))
700   
701 (defun process-cmd (user-cmd input-stream output-stream)
702   ;; Processes a user command. Returns t if the user-cmd was a top-level
703   ;; command
704   (cond ((eq user-cmd *eof-cmd*)
705          (when *exit-on-eof*
706            (quit))
707          (format output-stream "EOF~%")
708          t)
709         ((eq user-cmd *null-cmd*)
710          t)
711         ((eq (user-cmd-func user-cmd) :cmd-error)
712          (format output-stream "Unknown top-level command: ~s.~%"
713                  (user-cmd-input user-cmd))
714          (format output-stream "Type `:help' for the list of commands.~%")
715          t)
716         ((eq (user-cmd-func user-cmd) :history-error)
717          (format output-stream "Input numbered ~d is not on the history list~%"
718                  (user-cmd-input user-cmd))
719          t)
720         ((functionp (user-cmd-func user-cmd))
721          (add-to-history user-cmd)
722          (let ((*repl-output* output-stream)
723                (*repl-input* input-stream))
724            (apply (user-cmd-func user-cmd) (user-cmd-args user-cmd)))
725          (fresh-line)
726          t)
727         (t
728          (add-to-history user-cmd)
729          nil))) ; nope, not in my job description
730
731 (defun repl-read-form-fun (input-stream output-stream)
732   ;; Pick off all the leading ACL magic commands, then return a normal
733   ;; Lisp form.
734   (loop for user-cmd = (read-cmd input-stream) do
735         (if (process-cmd user-cmd input-stream output-stream)
736             (progn
737               (funcall sb-int:*repl-prompt-fun* output-stream)
738               (force-output output-stream))
739             (return (user-cmd-input user-cmd)))))
740
741
742 (setf sb-int:*repl-prompt-fun* #'repl-prompt-fun
743       sb-int:*repl-read-form-fun* #'repl-read-form-fun)
744
745 ;;; Break level processing
746
747 ;; use an initial break-level to hold current inspect toplevel at
748 ;; break-level 0
749
750 (defun new-break (&key restarts inspect continuable)
751   (push
752    (make-break-data :level (length *break-stack*)
753                     :restarts restarts
754                     :inspect inspect
755                     :inspect-initiated (when inspect t)
756                     :continuable continuable)
757    *break-stack*))
758
759 (defun set-break-inspect (inspect)
760   "sets the inspect data for the current break level"
761   (setf (break-data-inspect (car *break-stack*)) inspect))
762
763 ) ;; close special variables bindings
764