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