d3f523fe9a6487578ec1b11ec0df4f001fb910d8
[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:backtrace 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
163 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
164 ;;; one point (shown below), and SBCL cross-compiled it without
165 ;;; warning about FORMS being undefined. Check whether that problem
166 ;;; (missing warning) is repeatable in the final system and if so, fix
167 ;;; it.
168 #|
169 (defun infinite-error-protector ()
170   `(cond ((not *cold-init-complete-p*)
171           (%primitive print "Argh! error in cold init, halting")
172           (%primitive sb!c:halt))
173          ((or (not (boundp '*current-error-depth*))
174               (not (realp   *current-error-depth*))
175               (not (boundp '*maximum-error-depth*))
176               (not (realp   *maximum-error-depth*)))
177           (%primitive print "Argh! corrupted error depth, halting")
178           (%primitive sb!c:halt))
179          ((> *current-error-depth* *maximum-error-depth*)
180           (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
181           (error-error "Help! "
182                        *current-error-depth*
183                        " nested errors. "
184                        "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
185           (progn ,@forms)
186           t)
187          (t
188           (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
189           nil)))
190 |#
191 \f
192 ;;;; miscellaneous external functions
193
194 (defun sleep (seconds)
195   #!+sb-doc
196   "This function causes execution to be suspended for SECONDS. SECONDS may be
197 any non-negative real number."
198   (when (or (not (realp seconds))
199             (minusp seconds))
200     (error 'simple-type-error
201            :format-control "Invalid argument to SLEEP: ~S, ~
202                             should be a non-negative real."
203            :format-arguments (list seconds)
204            :datum seconds
205            :expected-type '(real 0)))
206   #!-(and win32 (not sb-thread))
207   (multiple-value-bind (sec nsec)
208       (if (integerp seconds)
209           (values seconds 0)
210           (multiple-value-bind (sec frac)
211               (truncate seconds)
212             (values sec (truncate frac 1e-9))))
213     ;; nanosleep() accepts time_t as the first argument, but on some platforms
214     ;; it is restricted to 100 million seconds. Maybe someone can actually
215     ;; have a reason to sleep for over 3 years?
216     (loop while (> sec (expt 10 8))
217           do (decf sec (expt 10 8))
218              (sb!unix:nanosleep (expt 10 8) 0))
219     (sb!unix:nanosleep sec nsec))
220   #!+(and win32 (not sb-thread))
221   (sb!win32:millisleep (truncate (* seconds 1000)))
222   nil)
223 \f
224 ;;;; the default toplevel function
225
226 (defvar / nil
227   #!+sb-doc
228   "a list of all the values returned by the most recent top level EVAL")
229 (defvar //  nil #!+sb-doc "the previous value of /")
230 (defvar /// nil #!+sb-doc "the previous value of //")
231 (defvar *   nil #!+sb-doc "the value of the most recent top level EVAL")
232 (defvar **  nil #!+sb-doc "the previous value of *")
233 (defvar *** nil #!+sb-doc "the previous value of **")
234 (defvar +   nil #!+sb-doc "the value of the most recent top level READ")
235 (defvar ++  nil #!+sb-doc "the previous value of +")
236 (defvar +++ nil #!+sb-doc "the previous value of ++")
237 (defvar -   nil #!+sb-doc "the form currently being evaluated")
238
239 (defun interactive-eval (form &key (eval #'eval))
240   #!+sb-doc
241   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
242 +++, ++, +, ///, //, /, and -."
243   (setf - form)
244   (unwind-protect
245        (let ((results (multiple-value-list (funcall eval form))))
246          (setf /// //
247                // /
248                / results
249                *** **
250                ** *
251                * (car results)))
252     (setf +++ ++
253           ++ +
254           + -))
255   (unless (boundp '*)
256     ;; The bogon returned an unbound marker.
257     ;; FIXME: It would be safer to check every one of the values in RESULTS,
258     ;; instead of just the first one.
259     (setf * nil)
260     (cerror "Go on with * set to NIL."
261             "EVAL returned an unbound marker."))
262   (values-list /))
263
264 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
265 ;;; output streams before proceeding.
266 (defun flush-standard-output-streams ()
267   (let ((null (make-broadcast-stream)))
268     (dolist (name '(*debug-io*
269                     *error-output*
270                     *query-io*
271                     *standard-output*
272                     *trace-output*
273                     *terminal-io*))
274       ;; 0. Pull out the underlying stream, so we know what it is.
275       ;; 1. Handle errors on it. We're doing this on entry to
276       ;;    debugger, so we don't want recursive errors here.
277       ;; 2. Rebind the stream symbol in case some poor sod sees
278       ;;    a broken stream here while running with *BREAK-ON-ERRORS*.
279       (let ((stream (stream-output-stream (symbol-value name))))
280         (progv (list name) (list null)
281           (handler-bind ((stream-error
282                            (lambda (c)
283                              (when (eq stream (stream-error-stream c))
284                                (go :next)))))
285             (force-output stream))))
286       :next))
287   (values))
288
289 (defun stream-output-stream (stream)
290   (typecase stream
291     (fd-stream
292      stream)
293     (synonym-stream
294      (stream-output-stream
295       (symbol-value (synonym-stream-symbol stream))))
296     (two-way-stream
297      (stream-output-stream
298       (two-way-stream-output-stream stream)))
299     (t
300      stream)))
301
302 (defun process-init-file (specified-pathname kind)
303   (multiple-value-bind (context default-function)
304       (ecase kind
305         (:system
306          (values "sysinit" *sysinit-pathname-function*))
307         (:user
308          (values "userinit" *userinit-pathname-function*)))
309     (if specified-pathname
310         (with-open-file (stream (parse-native-namestring specified-pathname)
311                                 :if-does-not-exist nil)
312           (if stream
313               (load-as-source stream :context context)
314               (cerror "Ignore missing init file"
315                       "The specified ~A file ~A was not found."
316                       context specified-pathname)))
317         (let ((default (funcall default-function)))
318           (when default
319             (with-open-file (stream (pathname default) :if-does-not-exist nil)
320               (when stream
321                 (load-as-source stream :context context))))))))
322
323 (defun process-eval/load-options (options)
324   (/show0 "handling --eval and --load options")
325   (flet ((process-1 (cons)
326            (destructuring-bind (opt . value) cons
327              (ecase opt
328                (:eval
329                 (with-simple-restart (continue "Ignore runtime option --eval ~S."
330                                                value)
331                   (multiple-value-bind (expr pos) (read-from-string value)
332                     (if (eq value (read-from-string value nil value :start pos))
333                         (eval expr)
334                         (error "Multiple expressions in --eval option: ~S"
335                                value)))))
336                (:load
337                 (with-simple-restart (continue "Ignore runtime option --load ~S."
338                                                value)
339                   (load (native-pathname value))))
340                (:quit
341                 (exit))))
342            (flush-standard-output-streams)))
343     (with-simple-restart (abort "Skip rest of --eval and --load options.")
344       (dolist (option options)
345         (process-1 option)))))
346
347 (defun process-script (script)
348   (flet ((load-script (stream)
349            ;; Scripts don't need to be stylish or fast, but silence is usually a
350            ;; desirable quality...
351            (handler-bind (((or style-warning compiler-note) #'muffle-warning)
352                           (stream-error (lambda (e)
353                                           ;; Shell-style.
354                                           (when (member (stream-error-stream e)
355                                                         (list *stdout* *stdin* *stderr*))
356                                             (exit)))))
357              ;; Let's not use the *TTY* for scripts, ok? Also, normally we use
358              ;; synonym streams, but in order to have the broken pipe/eof error
359              ;; handling right we want to bind them for scripts.
360              (let ((*terminal-io* (make-two-way-stream *stdin* *stdout*))
361                    (*debug-io* (make-two-way-stream *stdin* *stderr*))
362                    (*standard-input* *stdin*)
363                    (*standard-output* *stdout*)
364                    (*error-output* *stderr*))
365                (load stream :verbose nil :print nil)))))
366     (handling-end-of-the-world
367       (if (eq t script)
368           (load-script *stdin*)
369           (with-open-file (f (native-pathname script) :element-type :default)
370             (sb!fasl::maybe-skip-shebang-line f)
371             (load-script f))))))
372
373 ;; Errors while processing the command line cause the system to EXIT,
374 ;; instead of trying to go into the Lisp debugger, because trying to
375 ;; go into the Lisp debugger would get into various annoying issues of
376 ;; where we should go after the user tries to return from the
377 ;; debugger.
378 (defun startup-error (control-string &rest args)
379   (format *error-output*
380           "fatal error before reaching READ-EVAL-PRINT loop: ~%  ~?~%"
381           control-string
382           args)
383   (exit :code 1))
384
385 ;;; the default system top level function
386 (defun toplevel-init ()
387   (/show0 "entering TOPLEVEL-INIT")
388   (let ( ;; value of --sysinit option
389         (sysinit nil)
390         ;; t if --no-sysinit option given
391         (no-sysinit nil)
392         ;; value of --userinit option
393         (userinit nil)
394         ;; t if --no-userinit option given
395         (no-userinit nil)
396         ;; t if --disable-debugger option given
397         (disable-debugger nil)
398         ;; list of (<kind> . <string>) conses representing --eval and --load
399         ;; options. options. --eval options are stored as strings, so that
400         ;; they can be passed to READ only after their predecessors have been
401         ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
402         ;; creates a package referred to in the next EVAL form. Storing the
403         ;; original string also makes for easier debugging.
404         (reversed-options nil)
405         ;; Has a --noprint option been seen?
406         (noprint nil)
407         ;; Has a --script option been seen?
408         (script nil)
409         ;; Quit after processing other options?
410         (finally-quit nil)
411         ;; everything in *POSIX-ARGV* except for argv[0]=programname
412         (options (rest *posix-argv*)))
413
414     (declare (type list options))
415
416     (/show0 "done with outer LET in TOPLEVEL-INIT")
417
418     ;; FIXME: There are lots of ways for errors to happen around here
419     ;; (e.g. bad command line syntax, or READ-ERROR while trying to
420     ;; READ an --eval string). Make sure that they're handled
421     ;; reasonably.
422
423     ;; Process command line options.
424     (loop while options do
425          (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
426          (let ((option (first options)))
427            (flet ((pop-option ()
428                     (if options
429                         (pop options)
430                         (startup-error
431                          "unexpected end of command line options"))))
432              (cond ((string= option "--script")
433                     (pop-option)
434                     (setf disable-debugger t
435                           no-userinit t
436                           no-sysinit t
437                           script (if options (pop-option) t))
438                     (return))
439                    ((string= option "--sysinit")
440                     (pop-option)
441                     (if sysinit
442                         (startup-error "multiple --sysinit options")
443                         (setf sysinit (pop-option))))
444                    ((string= option "--no-sysinit")
445                     (pop-option)
446                     (setf no-sysinit t))
447                    ((string= option "--userinit")
448                     (pop-option)
449                     (if userinit
450                         (startup-error "multiple --userinit options")
451                         (setf userinit (pop-option))))
452                    ((string= option "--no-userinit")
453                     (pop-option)
454                     (setf no-userinit t))
455                    ((string= option "--eval")
456                     (pop-option)
457                     (push (cons :eval (pop-option)) reversed-options))
458                    ((string= option "--load")
459                     (pop-option)
460                     (push (cons :load (pop-option)) reversed-options))
461                    ((string= option "--noprint")
462                     (pop-option)
463                     (setf noprint t))
464                    ((string= option "--disable-debugger")
465                     (pop-option)
466                     (setf disable-debugger t))
467                    ((string= option "--quit")
468                     (pop-option)
469                     (setf finally-quit t))
470                    ((string= option "--non-interactive")
471                     ;; This option is short for --quit and --disable-debugger,
472                     ;; which are needed in combination for reliable non-
473                     ;; interactive startup.
474                     (pop-option)
475                     (setf finally-quit t)
476                     (setf disable-debugger t))
477                    ((string= option "--end-toplevel-options")
478                     (pop-option)
479                     (return))
480                    (t
481                     ;; Anything we don't recognize as a toplevel
482                     ;; option must be the start of user-level
483                     ;; options.. except that if we encounter
484                     ;; "--end-toplevel-options" after we gave up
485                     ;; because we didn't recognize an option as a
486                     ;; toplevel option, then the option we gave up on
487                     ;; must have been an error. (E.g. in
488                     ;;  "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
489                     ;; this test will let us detect that the string
490                     ;; "--eval(b)" is an error.)
491                     (if (find "--end-toplevel-options" options
492                               :test #'string=)
493                         (startup-error "bad toplevel option: ~S"
494                                        (first options))
495                         (return)))))))
496     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
497
498     ;; Delete all the options that we processed, so that only
499     ;; user-level options are left visible to user code.
500     (setf (rest *posix-argv*) options)
501
502     ;; Disable debugger before processing initialization files & co.
503     (when disable-debugger
504       (sb!ext:disable-debugger))
505
506     ;; Handle initialization files.
507     (/show0 "handling initialization files in TOPLEVEL-INIT")
508     ;; This CATCH is needed for the debugger command TOPLEVEL to
509     ;; work.
510     (catch 'toplevel-catcher
511       ;; We wrap all the pre-REPL user/system customized startup
512       ;; code in a restart.
513       ;;
514       ;; (Why not wrap everything, even the stuff above, in this
515       ;; restart? Errors above here are basically command line
516       ;; or Unix environment errors, e.g. a missing file or a
517       ;; typo on the Unix command line, and you don't need to
518       ;; get into Lisp to debug them, you should just start over
519       ;; and do it right at the Unix level. Errors below here
520       ;; are generally errors in user Lisp code, and it might be
521       ;; helpful to let the user reach the REPL in order to help
522       ;; figure out what's going on.)
523       (restart-case
524           (progn
525             (unless no-sysinit
526               (process-init-file sysinit :system))
527             (unless no-userinit
528               (process-init-file userinit :user))
529             (when finally-quit
530               (push (list :quit) reversed-options))
531             (process-eval/load-options (nreverse reversed-options))
532             (when script
533               (process-script script)
534               (bug "PROCESS-SCRIPT returned")))
535         (abort ()
536           :report (lambda (s)
537                     (write-string
538                      (if script
539                          ;; In case script calls (enable-debugger)!
540                          "Abort script, exiting lisp."
541                          "Skip to toplevel READ/EVAL/PRINT loop.")
542                      s))
543           (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
544           (values))                     ; (no-op, just fall through)
545         (exit ()
546           :report "Exit SBCL (calling #'EXIT, killing the process)."
547           :test (lambda (c) (declare (ignore c)) (not script))
548           (/show0 "falling through to EXIT from pre-REPL RESTART-CASE")
549           (exit :code 1))))
550
551     ;; one more time for good measure, in case we fell out of the
552     ;; RESTART-CASE above before one of the flushes in the ordinary
553     ;; flow of control had a chance to operate
554     (flush-standard-output-streams)
555
556     (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
557     (toplevel-repl noprint)
558     ;; (classic CMU CL error message: "You're certainly a clever child.":-)
559     (critically-unreachable "after TOPLEVEL-REPL")))
560
561 ;;; hooks to support customized toplevels like ACL-style toplevel from
562 ;;; KMR on sbcl-devel 2002-12-21.  Altered by CSR 2003-11-16 for
563 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
564 (defvar *repl-read-form-fun* #'repl-read-form-fun
565   #!+sb-doc
566   "A function of two stream arguments IN and OUT for the toplevel REPL to
567 call: Return the next Lisp form to evaluate (possibly handling other magic --
568 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
569 stream is there to support magic which requires issuing new prompts.")
570 (defvar *repl-prompt-fun* #'repl-prompt-fun
571   #!+sb-doc
572   "A function of one argument STREAM for the toplevel REPL to call: Prompt
573 the user for input.")
574 (defvar *repl-fun-generator* (constantly #'repl-fun)
575   #!+sb-doc
576   "A function of no arguments returning a function of one argument NOPRINT
577 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
578 *STANDARD-OUTPUT* are set up.")
579
580 ;;; read-eval-print loop for the default system toplevel
581 (defun toplevel-repl (noprint)
582   (/show0 "entering TOPLEVEL-REPL")
583   (let ((* nil) (** nil) (*** nil)
584         (- nil)
585         (+ nil) (++ nil) (+++ nil)
586         (/// nil) (// nil) (/ nil))
587     (/show0 "about to funcall *REPL-FUN-GENERATOR*")
588     (let ((repl-fun (funcall *repl-fun-generator*)))
589       ;; Each REPL in a multithreaded world should have bindings of
590       ;; most CL specials (most critically *PACKAGE*).
591       (with-rebound-io-syntax
592           (handler-bind ((step-condition 'invoke-stepper))
593             (loop
594                (/show0 "about to set up restarts in TOPLEVEL-REPL")
595                ;; CLHS recommends that there should always be an
596                ;; ABORT restart; we have this one here, and one per
597                ;; debugger level.
598                (with-simple-restart
599                    (abort "~@<Exit debugger, returning to top level.~@:>")
600                  (catch 'toplevel-catcher
601                    ;; In the event of a control-stack-exhausted-error, we
602                    ;; should have unwound enough stack by the time we get
603                    ;; here that this is now possible.
604                    #!-win32
605                    (sb!kernel::reset-control-stack-guard-page)
606                    (funcall repl-fun noprint)
607                    (critically-unreachable "after REPL")))))))))
608
609 ;;; Our default REPL prompt is the minimal traditional one.
610 (defun repl-prompt-fun (stream)
611   (fresh-line stream)
612   (write-string "* " stream)) ; arbitrary but customary REPL prompt
613
614 ;;; Our default form reader does relatively little magic, but does
615 ;;; handle the Unix-style EOF-is-end-of-process convention.
616 (defun repl-read-form-fun (in out)
617   (declare (type stream in out) (ignore out))
618   ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
619   ;; recovered from -- flip it here.
620   (when *read-suppress*
621     (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
622     (setf *read-suppress* nil))
623   (let* ((eof-marker (cons nil nil))
624          (form (read in nil eof-marker)))
625     (if (eq form eof-marker)
626         (exit)
627         form)))
628
629 (defun repl-fun (noprint)
630   (/show0 "entering REPL")
631   (loop
632    (unwind-protect
633         (progn
634           ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
635           (scrub-control-stack)
636           (sb!thread::get-foreground)
637           (unless noprint
638             (flush-standard-output-streams)
639             (funcall *repl-prompt-fun* *standard-output*)
640             ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
641             ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
642             ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
643             ;; odd. But maybe there *is* a valid reason in some
644             ;; circumstances? perhaps some deadlock issue when being driven
645             ;; by another process or something...)
646             (force-output *standard-output*))
647           (let* ((form (funcall *repl-read-form-fun*
648                                 *standard-input*
649                                 *standard-output*))
650                  (results (multiple-value-list (interactive-eval form))))
651             (unless noprint
652               (dolist (result results)
653                 (fresh-line)
654                 (prin1 result)))))
655      ;; If we started stepping in the debugger we want to stop now.
656      (disable-stepping))))
657 \f
658 ;;; a convenient way to get into the assembly-level debugger
659 (defun %halt ()
660   (%primitive sb!c:halt))