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