fix sleep on most ratios
[sbcl.git] / src / code / toplevel.lisp
1 ;;;; stuff related to the toplevel read-eval-print loop, plus some
2 ;;;; other miscellaneous functions that we don't have any better place
3 ;;;; for
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!IMPL")
15 \f
16 ;;;; magic specials initialized by GENESIS
17
18 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
19 ;;; of all static symbols in early-impl.lisp.
20 (progn
21   (defvar sb!vm::*current-catch-block*)
22   (defvar sb!vm::*current-unwind-protect-block*)
23   #!+hpux (defvar sb!vm::*c-lra*)
24   (defvar *free-interrupt-context-index*))
25 \f
26 ;;; specials initialized by !COLD-INIT
27
28 ;;; FIXME: These could be converted to DEFVARs.
29 (declaim (special #!+(or x86 x86-64) *pseudo-atomic-bits*
30                   *allow-with-interrupts*
31                   *interrupts-enabled*
32                   *interrupt-pending*
33                   #!+sb-thruption *thruption-pending*
34                   *type-system-initialized*))
35
36 (defvar *cold-init-complete-p*)
37
38 ;;; counts of nested errors (with internal errors double-counted)
39 (defvar *maximum-error-depth*)
40 (defvar *current-error-depth*)
41
42 ;;;; default initfiles
43
44 (defun sysinit-pathname ()
45   (or (let ((sbcl-homedir (sbcl-homedir-pathname)))
46         (when sbcl-homedir
47           (probe-file (merge-pathnames "sbclrc" sbcl-homedir))))
48       #!+win32
49       (merge-pathnames "sbcl\\sbclrc"
50                        (sb!win32::get-folder-pathname
51                         sb!win32::csidl_common_appdata))
52       #!-win32
53       "/etc/sbclrc"))
54
55 (defun userinit-pathname ()
56   (merge-pathnames ".sbclrc" (user-homedir-pathname)))
57
58 (defvar *sysinit-pathname-function* #'sysinit-pathname
59   #!+sb-doc
60   "Designator for a function of zero arguments called to obtain a
61 pathname designator for the default sysinit file, or NIL. If the
62 function returns NIL, no sysinit file is used unless one has been
63 specified on the command-line.")
64
65 (defvar *userinit-pathname-function* #'userinit-pathname
66   #!+sb-doc
67   "Designator for a function of zero arguments called to obtain a
68 pathname designator or a stream for the default userinit file, or NIL.
69 If the function returns NIL, no userinit file is used unless one has
70 been specified on the command-line.")
71
72 \f
73 ;;;; miscellaneous utilities for working with with TOPLEVEL
74
75 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
76 ;;; by QUIT) is caught and any final processing and return codes are
77 ;;; handled appropriately.
78 (defmacro handling-end-of-the-world (&body body)
79   `(without-interrupts
80      (catch '%end-of-the-world
81        (unwind-protect
82             (with-local-interrupts
83               (unwind-protect
84                    (progn ,@body)
85                 (call-exit-hooks)))
86          (%exit)))))
87
88 (defvar *exit-lock*)
89 (defvar *exit-in-process* nil)
90 (declaim (type (or null real) *exit-timeout*))
91 (defvar *exit-timeout* 60
92   "Default amount of seconds, if any, EXIT should wait for other
93 threads to finish after terminating them. Default value is 60. NIL
94 means to wait indefinitely.")
95
96 (defun os-exit-handler (condition)
97   (declare (ignore condition))
98   (os-exit *exit-in-process* :abort t))
99
100 (defvar *exit-error-handler* #'os-exit-handler)
101
102 (defun call-exit-hooks ()
103   (unless *exit-in-process*
104     (setf *exit-in-process* 0))
105   (handler-bind ((serious-condition *exit-error-handler*))
106     (call-hooks "exit" *exit-hooks* :on-error :warn)))
107
108 (defun %exit ()
109   ;; If anything goes wrong, we will exit immediately and forcibly.
110   (handler-bind ((serious-condition *exit-error-handler*))
111     (let ((ok nil)
112           (code *exit-in-process*))
113       (if (consp code)
114           ;; Another thread called EXIT, and passed the buck to us -- only
115           ;; final call left to do.
116           (os-exit (car code) :abort nil)
117           (unwind-protect
118                (progn
119                  (flush-standard-output-streams)
120                  (sb!thread::%exit-other-threads)
121                  (setf ok t))
122             (os-exit code :abort (not ok)))))))
123 \f
124 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
125
126 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
127 ;;; of hyperspace.
128 (defmacro infinite-error-protect (&rest forms)
129   `(unless (infinite-error-protector)
130      (/show0 "back from INFINITE-ERROR-PROTECTOR")
131      (let ((*current-error-depth* (1+ *current-error-depth*)))
132        (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
133        ;; arbitrary truncation
134        #!+sb-show (sb!debug:print-backtrace :count 8)
135        ,@forms)))
136
137 ;;; a helper function for INFINITE-ERROR-PROTECT
138 (defun infinite-error-protector ()
139   (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
140   (/hexstr *current-error-depth*)
141   (cond ((not *cold-init-complete-p*)
142          (%primitive print "Argh! error in cold init, halting")
143          (%primitive sb!c:halt))
144         ((or (not (boundp '*current-error-depth*))
145              (not (realp   *current-error-depth*))
146              (not (boundp '*maximum-error-depth*))
147              (not (realp   *maximum-error-depth*)))
148          (%primitive print "Argh! corrupted error depth, halting")
149          (%primitive sb!c:halt))
150         ((> *current-error-depth* *maximum-error-depth*)
151          (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
152          (/hexstr *maximum-error-depth*)
153          (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
154          (error-error "Help! "
155                       *current-error-depth*
156                       " nested errors. "
157                       "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
158          t)
159         (t
160          (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
161          nil)))
162 \f
163 ;;;; miscellaneous external functions
164
165 (defun split-seconds-for-sleep (seconds)
166   (declare (optimize speed))
167   (flet ((split-float ()
168            ;; KLUDGE: This whole thing to avoid consing floats
169            (let ((whole-seconds (truly-the fixnum (%unary-truncate seconds))))
170              (values whole-seconds
171                      (truly-the fixnum
172                                 (%unary-truncate (* (- seconds whole-seconds)
173                                                     (load-time-value 1s9 t))))))))
174     (declare (inline split-float))
175     (typecase seconds
176       ((single-float 0s0 #.(float most-positive-fixnum 1s0))
177        (split-float))
178       ((double-float 0d0 #.(float most-positive-fixnum 1d0))
179        (split-float))
180       (ratio
181        (multiple-value-bind (quot rem) (truncate (numerator seconds)
182                                                  (denominator seconds))
183          (values quot
184                  (truncate (* rem (/ 1000000000 (denominator seconds)))))))
185       (t
186        (multiple-value-bind (sec frac)
187            (truncate seconds)
188          (values sec (truncate frac (load-time-value 1s-9 t))))))))
189
190 (defun sleep (seconds)
191   #!+sb-doc
192   "This function causes execution to be suspended for SECONDS. SECONDS may be
193 any non-negative real number."
194   (when (or (not (realp seconds))
195             (minusp seconds))
196     (error 'simple-type-error
197            :format-control "Invalid argument to SLEEP: ~S, ~
198                             should be a non-negative real."
199            :format-arguments (list seconds)
200            :datum seconds
201            :expected-type '(real 0)))
202   #!-(and win32 (not sb-thread))
203   (multiple-value-bind (sec nsec)
204       (if (integerp seconds)
205           (values seconds 0)
206           (split-seconds-for-sleep seconds))
207     ;; nanosleep() accepts time_t as the first argument, but on some platforms
208     ;; it is restricted to 100 million seconds. Maybe someone can actually
209     ;; have a reason to sleep for over 3 years?
210     (loop while (> sec (expt 10 8))
211           do (decf sec (expt 10 8))
212              (sb!unix:nanosleep (expt 10 8) 0))
213     (sb!unix:nanosleep sec nsec))
214   #!+(and win32 (not sb-thread))
215   (sb!win32:millisleep (truncate (* seconds 1000)))
216   nil)
217 \f
218 ;;;; the default toplevel function
219
220 (defvar / nil
221   #!+sb-doc
222   "a list of all the values returned by the most recent top level EVAL")
223 (defvar //  nil #!+sb-doc "the previous value of /")
224 (defvar /// nil #!+sb-doc "the previous value of //")
225 (defvar *   nil #!+sb-doc "the value of the most recent top level EVAL")
226 (defvar **  nil #!+sb-doc "the previous value of *")
227 (defvar *** nil #!+sb-doc "the previous value of **")
228 (defvar +   nil #!+sb-doc "the value of the most recent top level READ")
229 (defvar ++  nil #!+sb-doc "the previous value of +")
230 (defvar +++ nil #!+sb-doc "the previous value of ++")
231 (defvar -   nil #!+sb-doc "the form currently being evaluated")
232
233 (defun interactive-eval (form &key (eval #'eval))
234   #!+sb-doc
235   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
236 +++, ++, +, ///, //, /, and -."
237   (setf - form)
238   (unwind-protect
239        (let ((results (multiple-value-list (funcall eval form))))
240          (setf /// //
241                // /
242                / results
243                *** **
244                ** *
245                * (car results)))
246     (setf +++ ++
247           ++ +
248           + -))
249   (unless (boundp '*)
250     ;; The bogon returned an unbound marker.
251     ;; FIXME: It would be safer to check every one of the values in RESULTS,
252     ;; instead of just the first one.
253     (setf * nil)
254     (cerror "Go on with * set to NIL."
255             "EVAL returned an unbound marker."))
256   (values-list /))
257
258 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
259 ;;; output streams before proceeding.
260 (defun flush-standard-output-streams ()
261   (let ((null (make-broadcast-stream)))
262     (dolist (name '(*debug-io*
263                     *error-output*
264                     *query-io*
265                     *standard-output*
266                     *trace-output*
267                     *terminal-io*))
268       ;; 0. Pull out the underlying stream, so we know what it is.
269       ;; 1. Handle errors on it. We're doing this on entry to
270       ;;    debugger, so we don't want recursive errors here.
271       ;; 2. Rebind the stream symbol in case some poor sod sees
272       ;;    a broken stream here while running with *BREAK-ON-ERRORS*.
273       (let ((stream (stream-output-stream (symbol-value name))))
274         (progv (list name) (list null)
275           (handler-bind ((stream-error
276                            (lambda (c)
277                              (when (eq stream (stream-error-stream c))
278                                (go :next)))))
279             (force-output stream))))
280       :next))
281   (values))
282
283 (defun stream-output-stream (stream)
284   (typecase stream
285     (fd-stream
286      stream)
287     (synonym-stream
288      (stream-output-stream
289       (symbol-value (synonym-stream-symbol stream))))
290     (two-way-stream
291      (stream-output-stream
292       (two-way-stream-output-stream stream)))
293     (t
294      stream)))
295
296 (defun process-init-file (specified-pathname kind)
297   (multiple-value-bind (context default-function)
298       (ecase kind
299         (:system
300          (values "sysinit" *sysinit-pathname-function*))
301         (:user
302          (values "userinit" *userinit-pathname-function*)))
303     (if specified-pathname
304         (with-open-file (stream (parse-native-namestring specified-pathname)
305                                 :if-does-not-exist nil)
306           (if stream
307               (load-as-source stream :context context)
308               (cerror "Ignore missing init file"
309                       "The specified ~A file ~A was not found."
310                       context specified-pathname)))
311         (let ((default (funcall default-function)))
312           (when default
313             (with-open-file (stream (pathname default) :if-does-not-exist nil)
314               (when stream
315                 (load-as-source stream :context context))))))))
316
317 (defun process-eval/load-options (options)
318   (/show0 "handling --eval and --load options")
319   (flet ((process-1 (cons)
320            (destructuring-bind (opt . value) cons
321              (ecase opt
322                (:eval
323                 (with-simple-restart (continue "Ignore runtime option --eval ~S."
324                                                value)
325                   (multiple-value-bind (expr pos) (read-from-string value)
326                     (if (eq value (read-from-string value nil value :start pos))
327                         (eval expr)
328                         (error "Multiple expressions in --eval option: ~S"
329                                value)))))
330                (:load
331                 (with-simple-restart (continue "Ignore runtime option --load ~S."
332                                                value)
333                   (load (native-pathname value))))
334                (:quit
335                 (exit))))
336            (flush-standard-output-streams)))
337     (with-simple-restart (abort "Skip rest of --eval and --load options.")
338       (dolist (option options)
339         (process-1 option)))))
340
341 (defun process-script (script)
342   (flet ((load-script (stream)
343            ;; Scripts don't need to be stylish or fast, but silence is usually a
344            ;; desirable quality...
345            (handler-bind (((or style-warning compiler-note) #'muffle-warning)
346                           (stream-error (lambda (e)
347                                           ;; Shell-style.
348                                           (when (member (stream-error-stream e)
349                                                         (list *stdout* *stdin* *stderr*))
350                                             (exit)))))
351              ;; Let's not use the *TTY* for scripts, ok? Also, normally we use
352              ;; synonym streams, but in order to have the broken pipe/eof error
353              ;; handling right we want to bind them for scripts.
354              (let ((*terminal-io* (make-two-way-stream *stdin* *stdout*))
355                    (*debug-io* (make-two-way-stream *stdin* *stderr*))
356                    (*standard-input* *stdin*)
357                    (*standard-output* *stdout*)
358                    (*error-output* *stderr*))
359                (load stream :verbose nil :print nil)))))
360     (handling-end-of-the-world
361       (if (eq t script)
362           (load-script *stdin*)
363           (with-open-file (f (native-pathname script) :element-type :default)
364             (sb!fasl::maybe-skip-shebang-line f)
365             (load-script f))))))
366
367 ;; Errors while processing the command line cause the system to EXIT,
368 ;; instead of trying to go into the Lisp debugger, because trying to
369 ;; go into the Lisp debugger would get into various annoying issues of
370 ;; where we should go after the user tries to return from the
371 ;; debugger.
372 (defun startup-error (control-string &rest args)
373   (format *error-output*
374           "fatal error before reaching READ-EVAL-PRINT loop: ~%  ~?~%"
375           control-string
376           args)
377   (exit :code 1))
378
379 ;;; the default system top level function
380 (defun toplevel-init ()
381   (/show0 "entering TOPLEVEL-INIT")
382   (let ( ;; value of --sysinit option
383         (sysinit nil)
384         ;; t if --no-sysinit option given
385         (no-sysinit nil)
386         ;; value of --userinit option
387         (userinit nil)
388         ;; t if --no-userinit option given
389         (no-userinit nil)
390         ;; t if --disable-debugger option given
391         (disable-debugger nil)
392         ;; list of (<kind> . <string>) conses representing --eval and --load
393         ;; options. options. --eval options are stored as strings, so that
394         ;; they can be passed to READ only after their predecessors have been
395         ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
396         ;; creates a package referred to in the next EVAL form. Storing the
397         ;; original string also makes for easier debugging.
398         (reversed-options nil)
399         ;; Has a --noprint option been seen?
400         (noprint nil)
401         ;; Has a --script option been seen?
402         (script nil)
403         ;; Quit after processing other options?
404         (finally-quit nil)
405         ;; everything in *POSIX-ARGV* except for argv[0]=programname
406         (options (rest *posix-argv*)))
407
408     (declare (type list options))
409
410     (/show0 "done with outer LET in TOPLEVEL-INIT")
411
412     ;; FIXME: There are lots of ways for errors to happen around here
413     ;; (e.g. bad command line syntax, or READ-ERROR while trying to
414     ;; READ an --eval string). Make sure that they're handled
415     ;; reasonably.
416
417     ;; Process command line options.
418     (loop while options do
419          (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
420          (let ((option (first options)))
421            (flet ((pop-option ()
422                     (if options
423                         (pop options)
424                         (startup-error
425                          "unexpected end of command line options"))))
426              (cond ((string= option "--script")
427                     (pop-option)
428                     (setf disable-debugger t
429                           no-userinit t
430                           no-sysinit t
431                           script (if options (pop-option) t))
432                     (return))
433                    ((string= option "--sysinit")
434                     (pop-option)
435                     (if sysinit
436                         (startup-error "multiple --sysinit options")
437                         (setf sysinit (pop-option))))
438                    ((string= option "--no-sysinit")
439                     (pop-option)
440                     (setf no-sysinit t))
441                    ((string= option "--userinit")
442                     (pop-option)
443                     (if userinit
444                         (startup-error "multiple --userinit options")
445                         (setf userinit (pop-option))))
446                    ((string= option "--no-userinit")
447                     (pop-option)
448                     (setf no-userinit t))
449                    ((string= option "--eval")
450                     (pop-option)
451                     (push (cons :eval (pop-option)) reversed-options))
452                    ((string= option "--load")
453                     (pop-option)
454                     (push (cons :load (pop-option)) reversed-options))
455                    ((string= option "--noprint")
456                     (pop-option)
457                     (setf noprint t))
458                    ((string= option "--disable-debugger")
459                     (pop-option)
460                     (setf disable-debugger t))
461                    ((string= option "--quit")
462                     (pop-option)
463                     (setf finally-quit t))
464                    ((string= option "--non-interactive")
465                     ;; This option is short for --quit and --disable-debugger,
466                     ;; which are needed in combination for reliable non-
467                     ;; interactive startup.
468                     (pop-option)
469                     (setf finally-quit t)
470                     (setf disable-debugger t))
471                    ((string= option "--end-toplevel-options")
472                     (pop-option)
473                     (return))
474                    (t
475                     ;; Anything we don't recognize as a toplevel
476                     ;; option must be the start of user-level
477                     ;; options.. except that if we encounter
478                     ;; "--end-toplevel-options" after we gave up
479                     ;; because we didn't recognize an option as a
480                     ;; toplevel option, then the option we gave up on
481                     ;; must have been an error. (E.g. in
482                     ;;  "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
483                     ;; this test will let us detect that the string
484                     ;; "--eval(b)" is an error.)
485                     (if (find "--end-toplevel-options" options
486                               :test #'string=)
487                         (startup-error "bad toplevel option: ~S"
488                                        (first options))
489                         (return)))))))
490     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
491
492     ;; Delete all the options that we processed, so that only
493     ;; user-level options are left visible to user code.
494     (when *posix-argv*
495       (setf (rest *posix-argv*) options))
496
497     ;; Disable debugger before processing initialization files & co.
498     (when disable-debugger
499       (sb!ext:disable-debugger))
500
501     ;; Handle initialization files.
502     (/show0 "handling initialization files in TOPLEVEL-INIT")
503     ;; This CATCH is needed for the debugger command TOPLEVEL to
504     ;; work.
505     (catch 'toplevel-catcher
506       ;; We wrap all the pre-REPL user/system customized startup
507       ;; code in a restart.
508       ;;
509       ;; (Why not wrap everything, even the stuff above, in this
510       ;; restart? Errors above here are basically command line
511       ;; or Unix environment errors, e.g. a missing file or a
512       ;; typo on the Unix command line, and you don't need to
513       ;; get into Lisp to debug them, you should just start over
514       ;; and do it right at the Unix level. Errors below here
515       ;; are generally errors in user Lisp code, and it might be
516       ;; helpful to let the user reach the REPL in order to help
517       ;; figure out what's going on.)
518       (restart-case
519           (progn
520             (unless no-sysinit
521               (process-init-file sysinit :system))
522             (unless no-userinit
523               (process-init-file userinit :user))
524             (when finally-quit
525               (push (list :quit) reversed-options))
526             (process-eval/load-options (nreverse reversed-options))
527             (when script
528               (process-script script)
529               (bug "PROCESS-SCRIPT returned")))
530         (abort ()
531           :report (lambda (s)
532                     (write-string
533                      (if script
534                          ;; In case script calls (enable-debugger)!
535                          "Abort script, exiting lisp."
536                          "Skip to toplevel READ/EVAL/PRINT loop.")
537                      s))
538           (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
539           (values))                     ; (no-op, just fall through)
540         (exit ()
541           :report "Exit SBCL (calling #'EXIT, killing the process)."
542           :test (lambda (c) (declare (ignore c)) (not script))
543           (/show0 "falling through to EXIT from pre-REPL RESTART-CASE")
544           (exit :code 1))))
545
546     ;; one more time for good measure, in case we fell out of the
547     ;; RESTART-CASE above before one of the flushes in the ordinary
548     ;; flow of control had a chance to operate
549     (flush-standard-output-streams)
550
551     (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
552     (toplevel-repl noprint)
553     ;; (classic CMU CL error message: "You're certainly a clever child.":-)
554     (critically-unreachable "after TOPLEVEL-REPL")))
555
556 ;;; hooks to support customized toplevels like ACL-style toplevel from
557 ;;; KMR on sbcl-devel 2002-12-21.  Altered by CSR 2003-11-16 for
558 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
559 (defvar *repl-read-form-fun* #'repl-read-form-fun
560   #!+sb-doc
561   "A function of two stream arguments IN and OUT for the toplevel REPL to
562 call: Return the next Lisp form to evaluate (possibly handling other magic --
563 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
564 stream is there to support magic which requires issuing new prompts.")
565 (defvar *repl-prompt-fun* #'repl-prompt-fun
566   #!+sb-doc
567   "A function of one argument STREAM for the toplevel REPL to call: Prompt
568 the user for input.")
569 (defvar *repl-fun-generator* (constantly #'repl-fun)
570   #!+sb-doc
571   "A function of no arguments returning a function of one argument NOPRINT
572 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
573 *STANDARD-OUTPUT* are set up.")
574
575 ;;; read-eval-print loop for the default system toplevel
576 (defun toplevel-repl (noprint)
577   (/show0 "entering TOPLEVEL-REPL")
578   (let ((* nil) (** nil) (*** nil)
579         (- nil)
580         (+ nil) (++ nil) (+++ nil)
581         (/// nil) (// nil) (/ nil))
582     (/show0 "about to funcall *REPL-FUN-GENERATOR*")
583     (let ((repl-fun (funcall *repl-fun-generator*)))
584       ;; Each REPL in a multithreaded world should have bindings of
585       ;; most CL specials (most critically *PACKAGE*).
586       (with-rebound-io-syntax
587           (handler-bind ((step-condition 'invoke-stepper))
588             (loop
589                (/show0 "about to set up restarts in TOPLEVEL-REPL")
590                ;; CLHS recommends that there should always be an
591                ;; ABORT restart; we have this one here, and one per
592                ;; debugger level.
593                (with-simple-restart
594                    (abort "~@<Exit debugger, returning to top level.~@:>")
595                  (catch 'toplevel-catcher
596                    ;; In the event of a control-stack-exhausted-error, we
597                    ;; should have unwound enough stack by the time we get
598                    ;; here that this is now possible.
599                    #!-win32
600                    (sb!kernel::reset-control-stack-guard-page)
601                    (funcall repl-fun noprint)
602                    (critically-unreachable "after REPL")))))))))
603
604 ;;; Our default REPL prompt is the minimal traditional one.
605 (defun repl-prompt-fun (stream)
606   (fresh-line stream)
607   (write-string "* " stream)) ; arbitrary but customary REPL prompt
608
609 ;;; Our default form reader does relatively little magic, but does
610 ;;; handle the Unix-style EOF-is-end-of-process convention.
611 (defun repl-read-form-fun (in out)
612   (declare (type stream in out) (ignore out))
613   ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
614   ;; recovered from -- flip it here.
615   (when *read-suppress*
616     (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
617     (setf *read-suppress* nil))
618   (let* ((eof-marker (cons nil nil))
619          (form (read in nil eof-marker)))
620     (if (eq form eof-marker)
621         (exit)
622         form)))
623
624 (defun repl-fun (noprint)
625   (/show0 "entering REPL")
626   (loop
627    (unwind-protect
628         (progn
629           ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
630           (scrub-control-stack)
631           (sb!thread::get-foreground)
632           (unless noprint
633             (flush-standard-output-streams)
634             (funcall *repl-prompt-fun* *standard-output*)
635             ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
636             ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
637             ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
638             ;; odd. But maybe there *is* a valid reason in some
639             ;; circumstances? perhaps some deadlock issue when being driven
640             ;; by another process or something...)
641             (force-output *standard-output*))
642           (let* ((form (funcall *repl-read-form-fun*
643                                 *standard-input*
644                                 *standard-output*))
645                  (results (multiple-value-list (interactive-eval form))))
646             (unless noprint
647               (dolist (result results)
648                 (fresh-line)
649                 (prin1 result)))))
650      ;; If we started stepping in the debugger we want to stop now.
651      (disable-stepping))))
652 \f
653 ;;; a convenient way to get into the assembly-level debugger
654 (defun %halt ()
655   (%primitive sb!c:halt))