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