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