1 ;;;; stuff related to the toplevel read-eval-print loop, plus some
2 ;;;; other miscellaneous functions that we don't have any better place
5 ;;;; This software is part of the SBCL system. See the README file for
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.
14 (in-package "SB!IMPL")
16 ;;;; magic specials initialized by GENESIS
18 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
19 ;;; of all static symbols in early-impl.lisp.
21 (defvar sb!vm::*current-catch-block*)
22 (defvar sb!vm::*current-unwind-protect-block*)
23 #!+hpux (defvar sb!vm::*c-lra*)
24 (defvar *free-interrupt-context-index*))
26 ;;; specials initialized by !COLD-INIT
28 ;;; FIXME: These could be converted to DEFVARs.
29 (declaim (special #!+(or x86 x86-64) *pseudo-atomic-bits*
30 *allow-with-interrupts*
33 #!+sb-thruption *thruption-pending*
34 *type-system-initialized*))
36 (defvar *cold-init-complete-p*)
38 ;;; counts of nested errors (with internal errors double-counted)
39 (defvar *maximum-error-depth*)
40 (defvar *current-error-depth*)
42 ;;;; default initfiles
44 (defun sysinit-pathname ()
45 (or (let ((sbcl-homedir (sbcl-homedir-pathname)))
47 (probe-file (merge-pathnames "sbclrc" sbcl-homedir))))
49 (merge-pathnames "sbcl\\sbclrc"
50 (sb!win32::get-folder-pathname
51 sb!win32::csidl_common_appdata))
55 (defun userinit-pathname ()
56 (merge-pathnames ".sbclrc" (user-homedir-pathname)))
58 (defvar *sysinit-pathname-function* #'sysinit-pathname
60 "Designator for a function of zero arguments called to obtain a
61 pathname designator for the default sysinit file, or NIL. If the
62 function returns NIL, no sysinit file is used unless one has been
63 specified on the command-line.")
65 (defvar *userinit-pathname-function* #'userinit-pathname
67 "Designator for a function of zero arguments called to obtain a
68 pathname designator or a stream for the default userinit file, or NIL.
69 If the function returns NIL, no userinit file is used unless one has
70 been specified on the command-line.")
73 ;;;; miscellaneous utilities for working with with TOPLEVEL
75 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
76 ;;; by QUIT) is caught and any final processing and return codes are
77 ;;; handled appropriately.
78 (defmacro handling-end-of-the-world (&body body)
80 (catch '%end-of-the-world
82 (with-local-interrupts
89 (defvar *exit-in-process* nil)
90 (declaim (type (or null real) *exit-timeout*))
91 (defvar *exit-timeout* 60
92 "Default amount of seconds, if any, EXIT should wait for other
93 threads to finish after terminating them. Default value is 60. NIL
94 means to wait indefinitely.")
96 (defun os-exit-handler (condition)
97 (declare (ignore condition))
98 (os-exit *exit-in-process* :abort t))
100 (defvar *exit-error-handler* #'os-exit-handler)
102 (defun call-exit-hooks ()
103 (unless *exit-in-process*
104 (setf *exit-in-process* 0))
105 (handler-bind ((serious-condition *exit-error-handler*))
106 (call-hooks "exit" *exit-hooks* :on-error :warn)))
109 ;; If anything goes wrong, we will exit immediately and forcibly.
110 (handler-bind ((serious-condition *exit-error-handler*))
112 (code *exit-in-process*))
114 ;; Another thread called EXIT, and passed the buck to us -- only
115 ;; final call left to do.
116 (os-exit (car code) :abort nil)
119 (flush-standard-output-streams)
120 (sb!thread::%exit-other-threads)
122 (os-exit code :abort (not ok)))))))
124 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
126 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
128 (defmacro infinite-error-protect (&rest forms)
129 `(unless (infinite-error-protector)
130 (/show0 "back from INFINITE-ERROR-PROTECTOR")
131 (let ((*current-error-depth* (1+ *current-error-depth*)))
132 (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
133 ;; arbitrary truncation
134 #!+sb-show (sb!debug:print-backtrace :count 8)
137 ;;; a helper function for INFINITE-ERROR-PROTECT
138 (defun infinite-error-protector ()
139 (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
140 (/hexstr *current-error-depth*)
141 (cond ((not *cold-init-complete-p*)
142 (%primitive print "Argh! error in cold init, halting")
143 (%primitive sb!c:halt))
144 ((or (not (boundp '*current-error-depth*))
145 (not (realp *current-error-depth*))
146 (not (boundp '*maximum-error-depth*))
147 (not (realp *maximum-error-depth*)))
148 (%primitive print "Argh! corrupted error depth, halting")
149 (%primitive sb!c:halt))
150 ((> *current-error-depth* *maximum-error-depth*)
151 (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
152 (/hexstr *maximum-error-depth*)
153 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
154 (error-error "Help! "
155 *current-error-depth*
157 "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
160 (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
163 ;;;; miscellaneous external functions
165 (defun split-seconds-for-sleep (seconds)
166 (declare (optimize speed))
167 ;; KLUDGE: This whole thing to avoid consing floats
168 (flet ((split-float ()
169 (let ((whole-seconds (truly-the fixnum (%unary-truncate seconds))))
170 (values whole-seconds
171 (truly-the (integer 0 #.(expt 10 9))
172 (%unary-truncate (* (- seconds (float whole-seconds))
173 (load-time-value 1f9 t))))))))
174 (declare (inline split-float))
176 ((single-float 0f0 #.(float most-positive-fixnum 1f0))
178 ((double-float 0d0 #.(float most-positive-fixnum 1d0))
181 (multiple-value-bind (quot rem) (truncate (numerator seconds)
182 (denominator seconds))
185 (if (typep 1000000000 'fixnum)
186 (truncate 1000000000 (denominator seconds))
187 ;; Can't truncate a bignum by a fixnum without consing
188 (* 10 (truncate 100000000 (denominator seconds))))))))
190 (multiple-value-bind (sec frac)
192 (values sec (truncate frac (load-time-value 1f-9 t))))))))
194 (defun sleep (seconds)
196 "This function causes execution to be suspended for SECONDS. SECONDS may be
197 any non-negative real number."
198 (when (or (not (realp seconds))
200 (error 'simple-type-error
201 :format-control "Invalid argument to SLEEP: ~S, ~
202 should be a non-negative real."
203 :format-arguments (list seconds)
205 :expected-type '(real 0)))
206 #!-(and win32 (not sb-thread))
207 (multiple-value-bind (sec nsec)
208 (if (integerp seconds)
210 (split-seconds-for-sleep seconds))
211 ;; nanosleep() accepts time_t as the first argument, but on some platforms
212 ;; it is restricted to 100 million seconds. Maybe someone can actually
213 ;; have a reason to sleep for over 3 years?
214 (loop while (> sec (expt 10 8))
215 do (decf sec (expt 10 8))
216 (sb!unix:nanosleep (expt 10 8) 0))
217 (sb!unix:nanosleep sec nsec))
218 #!+(and win32 (not sb-thread))
219 (sb!win32:millisleep (truncate (* seconds 1000)))
222 ;;;; the default toplevel function
226 "a list of all the values returned by the most recent top level EVAL")
227 (defvar // nil #!+sb-doc "the previous value of /")
228 (defvar /// nil #!+sb-doc "the previous value of //")
229 (defvar * nil #!+sb-doc "the value of the most recent top level EVAL")
230 (defvar ** nil #!+sb-doc "the previous value of *")
231 (defvar *** nil #!+sb-doc "the previous value of **")
232 (defvar + nil #!+sb-doc "the value of the most recent top level READ")
233 (defvar ++ nil #!+sb-doc "the previous value of +")
234 (defvar +++ nil #!+sb-doc "the previous value of ++")
235 (defvar - nil #!+sb-doc "the form currently being evaluated")
237 (defun interactive-eval (form &key (eval #'eval))
239 "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
240 +++, ++, +, ///, //, /, and -."
243 (let ((results (multiple-value-list (funcall eval form))))
254 ;; The bogon returned an unbound marker.
255 ;; FIXME: It would be safer to check every one of the values in RESULTS,
256 ;; instead of just the first one.
258 (cerror "Go on with * set to NIL."
259 "EVAL returned an unbound marker."))
262 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
263 ;;; output streams before proceeding.
264 (defun flush-standard-output-streams ()
265 (let ((null (make-broadcast-stream)))
266 (dolist (name '(*debug-io*
272 ;; 0. Pull out the underlying stream, so we know what it is.
273 ;; 1. Handle errors on it. We're doing this on entry to
274 ;; debugger, so we don't want recursive errors here.
275 ;; 2. Rebind the stream symbol in case some poor sod sees
276 ;; a broken stream here while running with *BREAK-ON-ERRORS*.
277 (let ((stream (stream-output-stream (symbol-value name))))
278 (progv (list name) (list null)
279 (handler-bind ((stream-error
281 (when (eq stream (stream-error-stream c))
283 (force-output stream))))
287 (defun stream-output-stream (stream)
292 (stream-output-stream
293 (symbol-value (synonym-stream-symbol stream))))
295 (stream-output-stream
296 (two-way-stream-output-stream stream)))
300 (defun process-init-file (specified-pathname kind)
301 (multiple-value-bind (context default-function)
304 (values "sysinit" *sysinit-pathname-function*))
306 (values "userinit" *userinit-pathname-function*)))
307 (if specified-pathname
308 (with-open-file (stream (parse-native-namestring specified-pathname)
309 :if-does-not-exist nil)
311 (load-as-source stream :context context)
312 (cerror "Ignore missing init file"
313 "The specified ~A file ~A was not found."
314 context specified-pathname)))
315 (let ((default (funcall default-function)))
317 (with-open-file (stream (pathname default) :if-does-not-exist nil)
319 (load-as-source stream :context context))))))))
321 (defun process-eval/load-options (options)
322 (/show0 "handling --eval and --load options")
323 (flet ((process-1 (cons)
324 (destructuring-bind (opt . value) cons
327 (with-simple-restart (continue "Ignore runtime option --eval ~S."
329 (multiple-value-bind (expr pos) (read-from-string value)
330 (if (eq value (read-from-string value nil value :start pos))
332 (error "Multiple expressions in --eval option: ~S"
335 (with-simple-restart (continue "Ignore runtime option --load ~S."
337 (load (native-pathname value))))
340 (flush-standard-output-streams)))
341 (with-simple-restart (abort "Skip rest of --eval and --load options.")
342 (dolist (option options)
343 (process-1 option)))))
345 (defun process-script (script)
346 (flet ((load-script (stream)
347 ;; Scripts don't need to be stylish or fast, but silence is usually a
348 ;; desirable quality...
349 (handler-bind (((or style-warning compiler-note) #'muffle-warning)
350 (stream-error (lambda (e)
352 (when (member (stream-error-stream e)
353 (list *stdout* *stdin* *stderr*))
355 ;; Let's not use the *TTY* for scripts, ok? Also, normally we use
356 ;; synonym streams, but in order to have the broken pipe/eof error
357 ;; handling right we want to bind them for scripts.
358 (let ((*terminal-io* (make-two-way-stream *stdin* *stdout*))
359 (*debug-io* (make-two-way-stream *stdin* *stderr*))
360 (*standard-input* *stdin*)
361 (*standard-output* *stdout*)
362 (*error-output* *stderr*))
363 (load stream :verbose nil :print nil)))))
364 (handling-end-of-the-world
366 (load-script *stdin*)
367 (with-open-file (f (native-pathname script) :element-type :default)
368 (sb!fasl::maybe-skip-shebang-line f)
371 ;; Errors while processing the command line cause the system to EXIT,
372 ;; instead of trying to go into the Lisp debugger, because trying to
373 ;; go into the Lisp debugger would get into various annoying issues of
374 ;; where we should go after the user tries to return from the
376 (defun startup-error (control-string &rest args)
377 (format *error-output*
378 "fatal error before reaching READ-EVAL-PRINT loop: ~% ~?~%"
383 ;;; the default system top level function
384 (defun toplevel-init ()
385 (/show0 "entering TOPLEVEL-INIT")
386 (let ( ;; value of --sysinit option
388 ;; t if --no-sysinit option given
390 ;; value of --userinit option
392 ;; t if --no-userinit option given
394 ;; t if --disable-debugger option given
395 (disable-debugger nil)
396 ;; list of (<kind> . <string>) conses representing --eval and --load
397 ;; options. options. --eval options are stored as strings, so that
398 ;; they can be passed to READ only after their predecessors have been
399 ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
400 ;; creates a package referred to in the next EVAL form. Storing the
401 ;; original string also makes for easier debugging.
402 (reversed-options nil)
403 ;; Has a --noprint option been seen?
405 ;; Has a --script option been seen?
407 ;; Quit after processing other options?
409 ;; everything in *POSIX-ARGV* except for argv[0]=programname
410 (options (rest *posix-argv*)))
412 (declare (type list options))
414 (/show0 "done with outer LET in TOPLEVEL-INIT")
416 ;; FIXME: There are lots of ways for errors to happen around here
417 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
418 ;; READ an --eval string). Make sure that they're handled
421 ;; Process command line options.
422 (loop while options do
423 (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
424 (let ((option (first options)))
425 (flet ((pop-option ()
429 "unexpected end of command line options"))))
430 (cond ((string= option "--script")
432 (setf disable-debugger t
435 script (if options (pop-option) t))
437 ((string= option "--sysinit")
440 (startup-error "multiple --sysinit options")
441 (setf sysinit (pop-option))))
442 ((string= option "--no-sysinit")
445 ((string= option "--userinit")
448 (startup-error "multiple --userinit options")
449 (setf userinit (pop-option))))
450 ((string= option "--no-userinit")
452 (setf no-userinit t))
453 ((string= option "--eval")
455 (push (cons :eval (pop-option)) reversed-options))
456 ((string= option "--load")
458 (push (cons :load (pop-option)) reversed-options))
459 ((string= option "--noprint")
462 ((string= option "--disable-debugger")
464 (setf disable-debugger t))
465 ((string= option "--quit")
467 (setf finally-quit t))
468 ((string= option "--non-interactive")
469 ;; This option is short for --quit and --disable-debugger,
470 ;; which are needed in combination for reliable non-
471 ;; interactive startup.
473 (setf finally-quit t)
474 (setf disable-debugger t))
475 ((string= option "--end-toplevel-options")
479 ;; Anything we don't recognize as a toplevel
480 ;; option must be the start of user-level
481 ;; options.. except that if we encounter
482 ;; "--end-toplevel-options" after we gave up
483 ;; because we didn't recognize an option as a
484 ;; toplevel option, then the option we gave up on
485 ;; must have been an error. (E.g. in
486 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
487 ;; this test will let us detect that the string
488 ;; "--eval(b)" is an error.)
489 (if (find "--end-toplevel-options" options
491 (startup-error "bad toplevel option: ~S"
494 (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
496 ;; Delete all the options that we processed, so that only
497 ;; user-level options are left visible to user code.
499 (setf (rest *posix-argv*) options))
501 ;; Disable debugger before processing initialization files & co.
502 (when disable-debugger
503 (sb!ext:disable-debugger))
505 ;; Handle initialization files.
506 (/show0 "handling initialization files in TOPLEVEL-INIT")
507 ;; This CATCH is needed for the debugger command TOPLEVEL to
509 (catch 'toplevel-catcher
510 ;; We wrap all the pre-REPL user/system customized startup
511 ;; code in a restart.
513 ;; (Why not wrap everything, even the stuff above, in this
514 ;; restart? Errors above here are basically command line
515 ;; or Unix environment errors, e.g. a missing file or a
516 ;; typo on the Unix command line, and you don't need to
517 ;; get into Lisp to debug them, you should just start over
518 ;; and do it right at the Unix level. Errors below here
519 ;; are generally errors in user Lisp code, and it might be
520 ;; helpful to let the user reach the REPL in order to help
521 ;; figure out what's going on.)
525 (process-init-file sysinit :system))
527 (process-init-file userinit :user))
529 (push (list :quit) reversed-options))
530 (process-eval/load-options (nreverse reversed-options))
532 (process-script script)
533 (bug "PROCESS-SCRIPT returned")))
538 ;; In case script calls (enable-debugger)!
539 "Abort script, exiting lisp."
540 "Skip to toplevel READ/EVAL/PRINT loop.")
542 (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
543 (values)) ; (no-op, just fall through)
545 :report "Exit SBCL (calling #'EXIT, killing the process)."
546 :test (lambda (c) (declare (ignore c)) (not script))
547 (/show0 "falling through to EXIT from pre-REPL RESTART-CASE")
550 ;; one more time for good measure, in case we fell out of the
551 ;; RESTART-CASE above before one of the flushes in the ordinary
552 ;; flow of control had a chance to operate
553 (flush-standard-output-streams)
555 (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
556 (toplevel-repl noprint)
557 ;; (classic CMU CL error message: "You're certainly a clever child.":-)
558 (critically-unreachable "after TOPLEVEL-REPL")))
560 ;;; hooks to support customized toplevels like ACL-style toplevel from
561 ;;; KMR on sbcl-devel 2002-12-21. Altered by CSR 2003-11-16 for
562 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
563 (defvar *repl-read-form-fun* #'repl-read-form-fun
565 "A function of two stream arguments IN and OUT for the toplevel REPL to
566 call: Return the next Lisp form to evaluate (possibly handling other magic --
567 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
568 stream is there to support magic which requires issuing new prompts.")
569 (defvar *repl-prompt-fun* #'repl-prompt-fun
571 "A function of one argument STREAM for the toplevel REPL to call: Prompt
572 the user for input.")
573 (defvar *repl-fun-generator* (constantly #'repl-fun)
575 "A function of no arguments returning a function of one argument NOPRINT
576 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
577 *STANDARD-OUTPUT* are set up.")
579 ;;; read-eval-print loop for the default system toplevel
580 (defun toplevel-repl (noprint)
581 (/show0 "entering TOPLEVEL-REPL")
582 (let ((* nil) (** nil) (*** nil)
584 (+ nil) (++ nil) (+++ nil)
585 (/// nil) (// nil) (/ nil))
586 (/show0 "about to funcall *REPL-FUN-GENERATOR*")
587 (let ((repl-fun (funcall *repl-fun-generator*)))
588 ;; Each REPL in a multithreaded world should have bindings of
589 ;; most CL specials (most critically *PACKAGE*).
590 (with-rebound-io-syntax
591 (handler-bind ((step-condition 'invoke-stepper))
593 (/show0 "about to set up restarts in TOPLEVEL-REPL")
594 ;; CLHS recommends that there should always be an
595 ;; ABORT restart; we have this one here, and one per
598 (abort "~@<Exit debugger, returning to top level.~@:>")
599 (catch 'toplevel-catcher
600 ;; In the event of a control-stack-exhausted-error, we
601 ;; should have unwound enough stack by the time we get
602 ;; here that this is now possible.
604 (sb!kernel::reset-control-stack-guard-page)
605 (funcall repl-fun noprint)
606 (critically-unreachable "after REPL")))))))))
608 ;;; Our default REPL prompt is the minimal traditional one.
609 (defun repl-prompt-fun (stream)
611 (write-string "* " stream)) ; arbitrary but customary REPL prompt
613 ;;; Our default form reader does relatively little magic, but does
614 ;;; handle the Unix-style EOF-is-end-of-process convention.
615 (defun repl-read-form-fun (in out)
616 (declare (type stream in out) (ignore out))
617 ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
618 ;; recovered from -- flip it here.
619 (when *read-suppress*
620 (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
621 (setf *read-suppress* nil))
622 (let* ((eof-marker (cons nil nil))
623 (form (read in nil eof-marker)))
624 (if (eq form eof-marker)
628 (defun repl-fun (noprint)
629 (/show0 "entering REPL")
633 ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
634 (scrub-control-stack)
635 (sb!thread::get-foreground)
637 (flush-standard-output-streams)
638 (funcall *repl-prompt-fun* *standard-output*)
639 ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
640 ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
641 ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
642 ;; odd. But maybe there *is* a valid reason in some
643 ;; circumstances? perhaps some deadlock issue when being driven
644 ;; by another process or something...)
645 (force-output *standard-output*))
646 (let* ((form (funcall *repl-read-form-fun*
649 (results (multiple-value-list (interactive-eval form))))
651 (dolist (result results)
654 ;; If we started stepping in the debugger we want to stop now.
655 (disable-stepping))))
657 ;;; a convenient way to get into the assembly-level debugger
659 (%primitive sb!c:halt))