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