0.7.12.30
[sbcl.git] / contrib / sb-aclrepl / sb-aclrepl.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 for this functionality is on the ACL website,
7 ;;;;   <http://www.franz.com/support/documentation/6.2/doc/top-level.htm>.
8
9 (cl:defpackage :sb-aclrepl
10   (:use :cl :sb-ext)
11   (:export :*prompt*)
12   ;; (what else should we be exporting?)
13   )
14
15 (cl:in-package :sb-aclrepl)
16
17 (eval-when (:compile-toplevel :load-toplevel :execute)
18   (defparameter *default-prompt* "~A(~d): "
19     "The default prompt."))
20 (defparameter *prompt* #.*default-prompt*
21   "The current prompt string or formatter function.")
22 (defparameter *use-short-package-name* t
23   "when T, use the shortnest package nickname in a prompt")
24 (defparameter *dir-stack* nil
25   "The top-level directory stack")
26 (defparameter *cmd-char* #\:
27   "Prefix character for a top-level command")
28 (defvar *max-history* 24
29   "Maximum number of history commands to remember")
30 (defvar *exit-on-eof*
31   "If T, then exit when the EOF character is entered.")
32 (defparameter *history* nil
33   "History list")
34 (defparameter *cmd-number* 0
35   "Number of the current command")
36
37 (defstruct user-cmd
38   (input nil) ; input, maybe a string or form
39   (func nil)  ; cmd func entered, overloaded (:eof :null-cmd))
40   (args nil)  ; args for cmd func
41   (hnum nil)) ; history number
42
43 (defvar *eof-marker* (cons :eof nil))
44 (defvar *eof-cmd* (make-user-cmd :func :eof))
45 (defvar *null-cmd* (make-user-cmd :func :null-cmd))
46
47 (defun prompt-package-name ()
48   (if *use-short-package-name*
49       (car (sort (append
50                   (package-nicknames cl:*package*)
51                   (list (package-name cl:*package*)))
52                  #'string-lessp))
53       (package-name cl:*package*)))
54
55 (defun read-cmd (input-stream)
56   (flet ((parse-args (parsing args-string)
57            (case parsing
58              (:string
59               (if (zerop (length args-string))
60                   nil
61                   (list args-string)))
62              (t
63               (let ((string-stream (make-string-input-stream args-string)))
64                 (loop as arg = (read string-stream nil *eof-marker*)
65                       until (eq arg *eof-marker*)
66                       collect arg))))))
67     (let ((next-char (peek-char-non-whitespace input-stream)))
68       (cond
69         ((eql next-char *cmd-char*)
70          (let* ((line (string-trim-whitespace (read-line input-stream)))
71                 (first-space-pos (position #\space line))
72                 (cmd-string (subseq line 1 first-space-pos))
73                 (cmd-args-string
74                  (if first-space-pos
75                      (string-trim-whitespace (subseq line first-space-pos))
76                      "")))
77            (if (numberp (read-from-string cmd-string))
78                (get-history (read-from-string cmd-string))
79                (let ((cmd-entry (find-cmd cmd-string)))
80                  (if cmd-entry
81                      (make-user-cmd :func (cmd-table-entry-func cmd-entry)
82                                     :input line
83                                     :args (parse-args
84                                            (cmd-table-entry-parsing cmd-entry)
85                                            cmd-args-string)
86                                     :hnum *cmd-number*)
87                      (progn
88                        (format t "Unknown top-level command: ~s.~%" cmd-string)
89                        (format t "Type `:help' for the list of commands.~%")
90                        *null-cmd*
91                        ))))))
92         ((eql next-char #\newline)
93          (read-char input-stream)
94          *null-cmd*)
95       (t
96        (let ((form (read input-stream nil *eof-marker*)))
97          (if (eq form *eof-marker*)
98              *eof-cmd*
99              (make-user-cmd :input form :func nil :hnum *cmd-number*))))))))
100  
101 (defparameter *cmd-table-hash*
102   (make-hash-table :size 30 :test #'equal))
103
104 ;;; cmd table entry
105 (defstruct cmd-table-entry
106   (name nil) ; name of command
107   (func nil) ; function handler
108   (desc nil) ; short description
109   (parsing nil) ; (:string :case-sensitive nil)
110   (group nil)) ; command group (:cmd or :alias)
111   
112 (defun make-cte (name-param func desc parsing group)
113   (let ((name (etypecase name-param
114                 (string
115                  name-param)
116                 (symbol
117                  (string-downcase (write-to-string name-param))))))
118     (make-cmd-table-entry :name name :func func :desc desc
119                           :parsing parsing :group group)))
120
121 (defun %add-entry (cmd &optional abbr-len)
122   (let* ((name (cmd-table-entry-name cmd))
123          (alen (if abbr-len
124                    abbr-len
125                    (length name))))
126     (dotimes (i (length name))
127       (when (>= i (1- alen))
128         (setf (gethash (subseq name 0 (1+ i)) *cmd-table-hash*)
129               cmd)))))
130
131 (defun add-cmd-table-entry (cmd-string abbr-len func-name desc parsing)
132   (%add-entry
133    (make-cte cmd-string (symbol-function func-name) desc parsing :cmd)
134    abbr-len))
135    
136 (defun find-cmd (cmdstr)
137   (gethash (string-downcase cmdstr) *cmd-table-hash*))
138
139 (defun user-cmd= (c1 c2)
140   "Returns T if two user commands are equal"
141   (if (or (not (user-cmd-p c1)) (not (user-cmd-p c2)))
142       (progn
143         (format t "Error: ~s or ~s is not a user-cmd" c1 c2)
144         nil)
145       (and (eq (user-cmd-func c1) (user-cmd-func c2))
146            (equal (user-cmd-args c1) (user-cmd-args c2))
147            (equal (user-cmd-input c1) (user-cmd-input c2)))))
148
149 (defun add-to-history (cmd)
150   (unless (and *history* (user-cmd= cmd (car *history*)))
151     (when (>= (length *history*) *max-history*)
152       (setq *history* (nbutlast *history* (+ (length *history*) *max-history* 1))))
153     (push cmd *history*)))
154
155 (defun get-history (n)
156   (let ((cmd (find n *history* :key #'user-cmd-hnum :test #'eql)))
157     (if cmd
158         cmd
159         (progn
160           (format t "Input numbered %d is not on the history list.." n)
161           *null-cmd*))))
162
163 (defun get-cmd-doc-list (&optional (group :cmd))
164   "Return list of all commands"
165   (let ((cmds '()))
166     (maphash (lambda (k v)
167                (when (and
168                       (eql (length k) (length (cmd-table-entry-name v)))
169                       (eq (cmd-table-entry-group v) group))
170                  (push (list k (cmd-table-entry-desc v)) cmds)))
171              *cmd-table-hash*)
172     (sort cmds #'string-lessp :key #'car)))
173
174 (defun cd-cmd (&optional string-dir)
175   (cond
176     ((or (zerop (length string-dir))
177          (string= string-dir "~"))
178      (setf cl:*default-pathname-defaults* (user-homedir-pathname)))
179     (t
180      (let ((new (truename string-dir)))
181        (when (pathnamep new)
182          (setf cl:*default-pathname-defaults* new)))))
183   (format t "~A~%" (namestring cl:*default-pathname-defaults*))
184   (values))
185
186 (defun pwd-cmd ()
187   (format t "Lisp's current working directory is ~s.~%"
188           (namestring cl:*default-pathname-defaults*))
189   (values))
190
191 (defun trace-cmd (&rest args)
192   (if args
193       (format t "~A~%" (eval (apply #'sb-debug::expand-trace args)))
194       (format t "~A~%" (sb-debug::%list-traced-funs)))
195   (values))
196
197 (defun untrace-cmd (&rest args)
198   (if args
199       (format t "~A~%"
200               (eval
201                (sb-int:collect ((res))
202                 (let ((current args))
203                   (loop
204                    (unless current (return))
205                    (let ((name (pop current)))
206                      (res (if (eq name :function)
207                               `(sb-debug::untrace-1 ,(pop current))
208                               `(sb-debug::untrace-1 ',name))))))
209                 `(progn ,@(res) t))))
210       (format t "~A~%" (eval (sb-debug::untrace-all))))
211   (values))
212
213 (defun exit-cmd (&optional (status 0))
214   (quit :unix-status status)
215   (values))
216
217 (defun package-cmd (&optional pkg)
218   (cond
219     ((null pkg)
220      (format t "The ~A package is current.~%" (package-name cl:*package*)))
221     ((null (find-package (write-to-string pkg)))
222      (format t "Unknown package: ~A.~%" pkg))
223     (t
224      (setf cl:*package* (find-package (write-to-string pkg)))))
225   (values))
226
227 (defun string-to-list-skip-spaces (str)
228   "Return a list of strings, delimited by spaces, skipping spaces."
229   (loop for i = 0 then (1+ j)
230         as j = (position #\space str :start i)
231         when (not (char= (char str i) #\space))
232         collect (subseq str i j) while j))
233
234 (defun ld-cmd (string-files)
235   (dolist (arg (string-to-list-skip-spaces string-files))
236     (format t "loading ~a~%" arg)
237     (load arg))
238   (values))
239
240 (defun cf-cmd (string-files)
241   (dolist (arg (string-to-list-skip-spaces string-files))
242     (compile-file arg))
243   (values))
244
245 (defun >-num (x y)
246   "Return if x and y are numbers, and x > y"
247   (and (numberp x) (numberp y) (> x y)))
248
249 (defun newer-file-p (file1 file2)
250   "Is file1 newer (written later than) file2?"
251   (>-num (if (probe-file file1) (file-write-date file1))
252          (if (probe-file file2) (file-write-date file2))))
253
254 (defun compile-file-as-needed (src-path)
255   "Compiles a file if needed, returns path."
256   (let ((dest-path (compile-file-pathname src-path)))
257     (when (or (not (probe-file dest-path))
258               (newer-file-p src-path dest-path))
259       (ensure-directories-exist dest-path)
260       (compile-file src-path :output-file dest-path))
261     dest-path))
262 \f
263 ;;;; implementation of commands
264
265 (defun cload-cmd (string-files)
266   (dolist (arg (string-to-list-skip-spaces string-files))
267     (load (compile-file-as-needed arg)))
268   (values))
269
270 (defun inspect-cmd (arg)
271   (eval `(inspect ,arg))
272   (values))
273
274 (defun describe-cmd (&rest args)
275   (dolist (arg args)
276     (eval `(describe ,arg)))
277   (values))
278
279 (defun macroexpand-cmd (arg)
280   (pprint (macroexpand arg))
281   (values))
282
283 (defun history-cmd ()
284   (let ((n (length *history*)))
285     (declare (fixnum n))
286     (dotimes (i n)
287       (declare (fixnum i))
288       (let ((hist (nth (- n i 1) *history*)))
289         (format t "~3A ~A~%" (user-cmd-hnum hist) (user-cmd-input hist)))))
290   (values))
291
292 (defun help-cmd (&optional cmd)
293   (cond
294     (cmd
295      (let ((cmd-entry (find-cmd cmd)))
296        (if cmd-entry
297            (format t "Documentation for ~A: ~A~%"
298                    (cmd-table-entry-name cmd-entry)
299                    (cmd-table-entry-desc cmd-entry)))))
300     (t
301      (format t "~13A ~a~%" "Command" "Description")
302      (format t "------------- -------------~%")
303      (dolist (doc-entry (get-cmd-doc-list :cmd))
304        (format t "~13A ~A~%" (car doc-entry) (cadr doc-entry)))))
305   (values))
306
307 (defun alias-cmd ()
308   (let ((doc-entries (get-cmd-doc-list :alias)))
309     (typecase doc-entries
310       (cons
311        (format t "~13A ~a~%" "Alias" "Description")
312        (format t "------------- -------------~%")
313        (dolist (doc-entry doc-entries)
314          (format t "~13A ~A~%" (car doc-entry) (cadr doc-entry))))
315       (t
316        (format t "No aliases are defined~%"))))
317   (values))
318
319 (defun shell-cmd (string-arg)
320   (sb-ext:run-program "/bin/sh" (list "-c" string-arg)
321                       :input nil :output *trace-output*)
322   (values))
323
324 (defun pushd-cmd (string-arg)
325   (push string-arg *dir-stack*)
326   (cd-cmd string-arg)
327   (values))
328
329 (defun popd-cmd ()
330   (if *dir-stack*
331       (let ((dir (pop *dir-stack*)))
332         (cd-cmd dir))
333       (format t "No directory on stack to pop.~%"))
334   (values))
335
336 (defun dirs-cmd ()
337   (dolist (dir *dir-stack*)
338     (format t "~a~%" dir))
339   (values))
340 \f
341 ;;;; dispatch table for commands
342
343 (let ((cmd-table
344        '(("aliases" 3 alias-cmd "show aliases")
345          ("cd" 2 cd-cmd "change default diretory" :parsing :string)
346          ("ld" 2 ld-cmd "load a file" :parsing :string)
347          ("cf" 2 cf-cmd "compile file" :parsing :string)
348          ("cload" 2 cload-cmd "compile if needed and load file"
349           :parsing :string)
350          ("describe" 2 describe-cmd "describe an object")
351          ("macroexpand" 2 macroexpand-cmd "macroexpand an expression")
352          ("package" 2 package-cmd "change current package")
353          ("exit" 2 exit-cmd "exit sbcl")
354          ("help" 2 help-cmd "print this help")
355          ("history" 3 history-cmd "print the recent history")
356          ("inspect" 2 inspect-cmd "inspect an object")
357          ("pwd" 3 pwd-cmd "print current directory")
358          ("pushd" 2 pushd-cmd "push directory on stack" :parsing :string)
359          ("popd" 2 popd-cmd "pop directory from stack")
360          ("trace" 2 trace-cmd "trace a function")
361          ("untrace" 4 untrace-cmd "untrace a function")
362          ("dirs" 2 dirs-cmd "show directory stack")
363          ("shell" 2 shell-cmd "execute a shell cmd" :parsing :string))))
364   (dolist (cmd cmd-table)
365     (destructuring-bind (cmd-string abbr-len func-name desc &key parsing) cmd
366       (add-cmd-table-entry cmd-string abbr-len func-name desc parsing))))
367 \f
368 ;;;; machinery for aliases
369
370 (defsetf alias (name) (user-func)
371   `(progn
372     (%add-entry
373      (make-cte (quote ,name) ,user-func "" nil :alias))
374     (quote ,name)))
375
376 (defmacro alias (name-param args &rest body)
377   (let ((parsing nil)
378         (desc "")
379         (abbr-index nil)
380         (name (if (atom name-param)
381                   name-param
382                   (car name-param))))
383     (when (consp name-param)
384      (dolist (param (cdr name-param))
385         (cond
386           ((or
387             (eq param :case-sensitive)
388             (eq param :string))
389            (setq parsing param))
390           ((stringp param)
391            (setq desc param))
392           ((numberp param)
393            (setq abbr-index param)))))
394     `(progn
395       (%add-entry
396        (make-cte (quote ,name) (lambda ,args ,@body) ,desc ,parsing :alias)
397        ,abbr-index)
398       ,name)))
399        
400     
401 (defun remove-alias (&rest aliases)
402   (let ((keys '())
403         (remove-all (not (null (find :all aliases)))))
404     (unless remove-all  ;; ensure all alias are strings
405       (setq aliases
406             (loop for alias in aliases
407                   collect
408                   (etypecase alias
409                     (string
410                      alias)
411                     (symbol
412                      (symbol-name alias))))))
413     (maphash
414      (lambda (key cmd)
415        (when (eq (cmd-table-entry-group cmd) :alias)
416          (if remove-all
417              (push key keys)
418              (when (some
419                     (lambda (alias)
420                       (let ((klen (length key)))
421                         (and (>= (length alias) klen)
422                              (string-equal (subseq alias 0 klen)
423                                            (subseq key 0 klen)))))
424                     aliases)
425                (push key keys)))))
426      *cmd-table-hash*)
427     (dolist (key keys)
428       (remhash key *cmd-table-hash*))
429     keys))
430 \f
431 ;;;; low-level reading/parsing functions
432
433 ;;; Skip white space (but not #\NEWLINE), and peek at the next
434 ;;; character.
435 (defun peek-char-non-whitespace (&optional stream)
436   (do ((char (peek-char nil stream nil *eof-marker*)
437              (peek-char nil stream nil *eof-marker*)))
438       ((not (whitespace-char-not-newline-p char)) char)
439     (read-char stream)))
440
441 (defun string-trim-whitespace (str)
442   (string-trim '(#\space #\tab #\return)
443                str))
444
445 (defun whitespace-char-not-newline-p (x)
446   (and (characterp x)
447        (or (char= x #\space)
448            (char= x #\tab)
449            (char= x #\return))))
450 \f
451 ;;;; linking into SBCL hooks
452
453 (defun repl-prompt-fun (stream)
454   (incf *cmd-number*)
455   (fresh-line stream)
456   (if (functionp *prompt*)
457       (write-string (funcall *prompt* (prompt-package-name) *cmd-number*)
458                     stream)
459       (format stream *prompt* (prompt-package-name) *cmd-number*)))
460   
461 ;;; If USER-CMD is to be processed as something magical (not an
462 ;;; ordinary eval-and-print-me form) then do so and return non-NIL.
463 (defun execute-as-acl-magic (user-cmd input-stream output-stream)
464   ;; kludgity kludge kludge kludge ("and then a miracle occurs")
465   ;;
466   ;; This is a really sloppy job of smashing KMR's code (what he
467   ;; called DEFUN REP-ONE-CMD) onto DB's hook ideas, not even doing
468   ;; the basics like passing INPUT-STREAM and OUTPUT-STREAM into the
469   ;; KMR code. A real implementation might want to do rather better.
470   (cond ((eq user-cmd *eof-cmd*)
471          (decf *cmd-number*)
472          (when *exit-on-eof*
473            (quit))
474          (format t "EOF~%")
475          t) ; Yup, we knew how to handle that.
476         ((eq user-cmd *null-cmd*)
477          (decf *cmd-number*)
478          t) ; Yup.
479         ((functionp (user-cmd-func user-cmd))
480          (apply (user-cmd-func user-cmd) (user-cmd-args user-cmd))
481          (add-to-history user-cmd)
482          (fresh-line)
483          t) ; Ayup.
484         (t
485          nil))) ; nope, not in my job description
486
487 (defun repl-read-form-fun (input-stream output-stream)
488   ;; Pick off all the leading ACL magic commands, then return a normal
489   ;; Lisp form.
490   (loop for user-cmd = (read-cmd input-stream) do
491         (if (execute-as-acl-magic user-cmd input-stream output-stream)
492             (progn
493               (repl-prompt-fun output-stream)
494               (force-output output-stream))
495             (return (user-cmd-input user-cmd)))))
496
497 (setf sb-int:*repl-prompt-fun* #'repl-prompt-fun
498       sb-int:*repl-read-form-fun* #'repl-read-form-fun)