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