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