Decentralize per-thread initial special bindings.
[sbcl.git] / src / code / toplevel.lisp
blob51b2d5f2bca06334a2b03dc8b72b7f224e6a87a3
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
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.
14 (in-package "SB!IMPL")
16 ;;;; default initfiles
18 (defun sysinit-pathname ()
19 (or (let ((sbcl-homedir (sbcl-homedir-pathname)))
20 (when sbcl-homedir
21 (probe-file (merge-pathnames "sbclrc" sbcl-homedir))))
22 #!+win32
23 (merge-pathnames "sbcl\\sbclrc"
24 (sb!win32::get-folder-pathname
25 sb!win32::csidl_common_appdata))
26 #!-win32
27 "/etc/sbclrc"))
29 (defun userinit-pathname ()
30 (merge-pathnames ".sbclrc" (user-homedir-pathname)))
32 (define-load-time-global *sysinit-pathname-function* #'sysinit-pathname
33 "Designator for a function of zero arguments called to obtain a
34 pathname designator for the default sysinit file, or NIL. If the
35 function returns NIL, no sysinit file is used unless one has been
36 specified on the command-line.")
38 (define-load-time-global *userinit-pathname-function* #'userinit-pathname
39 "Designator for a function of zero arguments called to obtain a
40 pathname designator or a stream for the default userinit file, or NIL.
41 If the function returns NIL, no userinit file is used unless one has
42 been specified on the command-line.")
45 ;;;; miscellaneous utilities for working with with TOPLEVEL
47 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
48 ;;; by QUIT) is caught and any final processing and return codes are
49 ;;; handled appropriately.
50 (defmacro handling-end-of-the-world (&body body)
51 `(without-interrupts
52 (catch '%end-of-the-world
53 (unwind-protect
54 (with-local-interrupts
55 (unwind-protect
56 (progn ,@body)
57 (call-exit-hooks)))
58 (%exit)))))
60 (define-load-time-global *exit-lock* nil)
61 (!define-thread-local *exit-in-process* nil)
62 (declaim (type (or null real) *exit-timeout*))
63 (defvar *exit-timeout* 60
64 "Default amount of seconds, if any, EXIT should wait for other
65 threads to finish after terminating them. Default value is 60. NIL
66 means to wait indefinitely.")
68 (defun os-exit-handler (condition)
69 (declare (ignore condition))
70 (os-exit *exit-in-process* :abort t))
72 (defvar *exit-error-handler* #'os-exit-handler)
74 (defun call-exit-hooks ()
75 (unless *exit-in-process*
76 (setf *exit-in-process* 0))
77 (handler-bind ((serious-condition *exit-error-handler*))
78 (call-hooks "exit" *exit-hooks* :on-error :warn)))
80 (defun %exit ()
81 ;; If anything goes wrong, we will exit immediately and forcibly.
82 (handler-bind ((serious-condition *exit-error-handler*))
83 (let ((ok nil)
84 (code *exit-in-process*))
85 (if (consp code)
86 ;; Another thread called EXIT, and passed the buck to us -- only
87 ;; final call left to do.
88 (os-exit (car code) :abort nil)
89 (unwind-protect
90 (progn
91 (flush-standard-output-streams)
92 (sb!thread::%exit-other-threads)
93 (setf ok t))
94 (os-exit code :abort (not ok)))))))
96 ;;;; miscellaneous external functions
98 (declaim (inline split-ratio-for-sleep))
99 (defun split-ratio-for-sleep (seconds)
100 (declare (ratio seconds)
101 (muffle-conditions t))
102 (multiple-value-bind (quot rem) (truncate (numerator seconds)
103 (denominator seconds))
104 (values quot
105 (* rem
106 #.(if (sb!xc:typep 1000000000 'fixnum)
107 '(truncate 1000000000 (denominator seconds))
108 ;; Can't truncate a bignum by a fixnum without consing
109 '(* 10 (truncate 100000000 (denominator seconds))))))))
111 (defun split-seconds-for-sleep (seconds)
112 (declare (muffle-conditions t))
113 ;; KLUDGE: This whole thing to avoid consing floats
114 (flet ((split-float ()
115 (let ((whole-seconds (truly-the fixnum (%unary-truncate seconds))))
116 (values whole-seconds
117 (truly-the (integer 0 #.(expt 10 9))
118 (%unary-truncate (* (- seconds (float whole-seconds seconds))
119 (load-time-value 1f9 t))))))))
120 (declare (inline split-float))
121 (typecase seconds
122 ((single-float 0f0 #.(float sb!xc:most-positive-fixnum 1f0))
123 (split-float))
124 ((double-float 0d0 #.(float sb!xc:most-positive-fixnum 1d0))
125 (split-float))
126 (ratio
127 (split-ratio-for-sleep seconds))
129 (multiple-value-bind (sec frac)
130 (truncate seconds)
131 (values sec (truncate frac (load-time-value 1f-9 t))))))))
133 (defun sleep (seconds)
134 "This function causes execution to be suspended for SECONDS. SECONDS may be
135 any non-negative real number."
136 (declare (explicit-check))
137 (when (or (not (realp seconds))
138 (minusp seconds))
139 (error 'simple-type-error
140 :format-control "Invalid argument to SLEEP: ~S, ~
141 should be a non-negative real."
142 :format-arguments (list seconds)
143 :datum seconds
144 :expected-type '(real 0)))
145 #!-(and win32 (not sb-thread))
146 (typecase seconds
147 #!-win32
148 (double-float
149 (sb!unix::nanosleep-double seconds))
150 #!-win32
151 (single-float
152 (sb!unix::nanosleep-float seconds))
154 (multiple-value-bind (sec nsec)
155 (if (integerp seconds)
156 (values seconds 0)
157 #!-win32
158 (split-ratio-for-sleep seconds)
159 #!+win32
160 (split-seconds-for-sleep seconds))
161 ;; nanosleep() accepts time_t as the first argument, but on some platforms
162 ;; it is restricted to 100 million seconds. Maybe someone can actually
163 ;; have a reason to sleep for over 3 years?
164 (loop while (> sec (expt 10 8))
165 do (decf sec (expt 10 8))
166 (sb!unix:nanosleep (expt 10 8) 0))
167 (sb!unix:nanosleep sec nsec))))
168 #!+(and win32 (not sb-thread))
169 (sb!win32:millisleep (truncate (* seconds 1000)))
170 nil)
172 ;;;; the default toplevel function
174 (defvar / nil
175 "a list of all the values returned by the most recent top level EVAL")
176 (defvar // nil "the previous value of /")
177 (defvar /// nil "the previous value of //")
178 (defvar * nil "the value of the most recent top level EVAL")
179 (defvar ** nil "the previous value of *")
180 (defvar *** nil "the previous value of **")
181 (defvar + nil "the value of the most recent top level READ")
182 (defvar ++ nil "the previous value of +")
183 (defvar +++ nil "the previous value of ++")
184 (defvar - nil "the form currently being evaluated")
186 (defun interactive-eval (form &key (eval #'eval))
187 "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
188 +++, ++, +, ///, //, /, and -."
189 (setf - form)
190 (unwind-protect
191 (let ((results (multiple-value-list (funcall eval form))))
192 (setf /// //
193 // /
194 / results
195 *** **
196 ** *
197 * (car results)))
198 (setf +++ ++
199 ++ +
200 + -))
201 (unless (boundp '*)
202 ;; The bogon returned an unbound marker.
203 ;; FIXME: It would be safer to check every one of the values in RESULTS,
204 ;; instead of just the first one.
205 (setf * nil)
206 (cerror "Go on with * set to NIL."
207 "EVAL returned an unbound marker."))
208 (values-list /))
210 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
211 ;;; output streams before proceeding.
212 (defun flush-standard-output-streams ()
213 (let ((null (make-broadcast-stream)))
214 (dolist (name '(*debug-io*
215 *error-output*
216 *query-io*
217 *standard-output*
218 *trace-output*
219 *terminal-io*))
220 ;; 0. Pull out the underlying stream, so we know what it is.
221 ;; 1. Handle errors on it. We're doing this on entry to
222 ;; debugger, so we don't want recursive errors here.
223 ;; 2. Rebind the stream symbol in case some poor sod sees
224 ;; a broken stream here while running with *BREAK-ON-ERRORS*.
225 (let ((stream (stream-output-stream (symbol-value name))))
226 ;; This is kind of crummy because it checks in globaldb for each
227 ;; stream symbol whether it can be bound to a stream. The translator
228 ;; for PROGV could skip ABOUT-TO-MODIFY-SYMBOL-VALUE based on
229 ;; an aspect of a policy, but if users figure that out they could
230 ;; do something horrible like rebind T and NIL.
231 (progv (list name) (list null)
232 (handler-bind ((stream-error
233 (lambda (c)
234 (when (eq stream (stream-error-stream c))
235 (go :next)))))
236 (force-output stream))))
237 :next))
238 (values))
240 (defun process-eval/load-options (options)
241 (/show0 "handling --eval and --load options")
242 (flet ((process-1 (cons)
243 (destructuring-bind (opt . value) cons
244 (ecase opt
245 (:eval
246 (with-simple-restart (continue "Ignore runtime option --eval ~S."
247 value)
248 (multiple-value-bind (expr pos) (read-from-string value)
249 (if (eq value (read-from-string value nil value :start pos))
250 (eval expr)
251 (error "Multiple expressions in --eval option: ~S"
252 value)))))
253 (:load
254 (with-simple-restart (continue "Ignore runtime option --load ~S."
255 value)
256 (load (native-pathname value))))
257 (:quit
258 (exit))))
259 (flush-standard-output-streams)))
260 (with-simple-restart (abort "Skip rest of --eval and --load options.")
261 (dolist (option options)
262 (process-1 option)))))
264 (defun process-script (script)
265 (flet ((load-script (stream)
266 ;; Scripts don't need to be stylish or fast, but silence is usually a
267 ;; desirable quality...
268 (handler-bind (((or style-warning compiler-note) #'muffle-warning)
269 (stream-error (lambda (e)
270 ;; Shell-style.
271 (when (member (stream-error-stream e)
272 (list *stdout* *stdin* *stderr*))
273 (exit)))))
274 ;; Let's not use the *TTY* for scripts, ok? Also, normally we use
275 ;; synonym streams, but in order to have the broken pipe/eof error
276 ;; handling right we want to bind them for scripts.
277 (let ((*terminal-io* (make-two-way-stream *stdin* *stdout*))
278 (*debug-io* (make-two-way-stream *stdin* *stderr*))
279 (*standard-input* *stdin*)
280 (*standard-output* *stdout*)
281 (*error-output* *stderr*))
282 (load stream :verbose nil :print nil)))))
283 (handling-end-of-the-world
284 (if (eq t script)
285 (load-script *stdin*)
286 (with-open-file (f (native-pathname script) :element-type :default)
287 (sb!fasl::maybe-skip-shebang-line f)
288 (load-script f))))))
290 ;; Errors while processing the command line cause the system to EXIT,
291 ;; instead of trying to go into the Lisp debugger, because trying to
292 ;; go into the Lisp debugger would get into various annoying issues of
293 ;; where we should go after the user tries to return from the
294 ;; debugger.
295 (defun startup-error (control-string &rest args)
296 (format *error-output*
297 "fatal error before reaching READ-EVAL-PRINT loop: ~% ~?~%"
298 control-string
299 args)
300 (exit :code 1))
302 ;;; the default system top level function
303 (defun toplevel-init ()
304 (/show0 "entering TOPLEVEL-INIT")
305 (let ( ;; value of --sysinit option
306 (sysinit nil)
307 ;; t if --no-sysinit option given
308 (no-sysinit nil)
309 ;; value of --userinit option
310 (userinit nil)
311 ;; t if --no-userinit option given
312 (no-userinit nil)
313 ;; t if --disable-debugger option given
314 (disable-debugger nil)
315 ;; list of (<kind> . <string>) conses representing --eval and --load
316 ;; options. options. --eval options are stored as strings, so that
317 ;; they can be passed to READ only after their predecessors have been
318 ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
319 ;; creates a package referred to in the next EVAL form. Storing the
320 ;; original string also makes for easier debugging.
321 (reversed-options nil)
322 ;; Has a --noprint option been seen?
323 (noprint nil)
324 ;; Has a --script option been seen?
325 (script nil)
326 ;; Quit after processing other options?
327 (finally-quit nil)
328 ;; everything in *POSIX-ARGV* except for argv[0]=programname
329 (options (rest *posix-argv*)))
331 (declare (type list options))
333 (/show0 "done with outer LET in TOPLEVEL-INIT")
335 ;; FIXME: There are lots of ways for errors to happen around here
336 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
337 ;; READ an --eval string). Make sure that they're handled
338 ;; reasonably.
340 ;; Process command line options.
341 (loop while options do
342 (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
343 (let ((option (first options)))
344 (flet ((pop-option ()
345 (if options
346 (pop options)
347 (startup-error
348 "unexpected end of command line options"))))
349 (cond ((string= option "--script")
350 (pop-option)
351 (setf disable-debugger t
352 no-userinit t
353 no-sysinit t
354 script (if options (pop-option) t))
355 (return))
356 ((string= option "--sysinit")
357 (pop-option)
358 (if sysinit
359 (startup-error "multiple --sysinit options")
360 (setf sysinit (pop-option))))
361 ((string= option "--no-sysinit")
362 (pop-option)
363 (setf no-sysinit t))
364 ((string= option "--userinit")
365 (pop-option)
366 (if userinit
367 (startup-error "multiple --userinit options")
368 (setf userinit (pop-option))))
369 ((string= option "--no-userinit")
370 (pop-option)
371 (setf no-userinit t))
372 ((string= option "--eval")
373 (pop-option)
374 (push (cons :eval (pop-option)) reversed-options))
375 ((string= option "--load")
376 (pop-option)
377 (push (cons :load (pop-option)) reversed-options))
378 ((string= option "--noprint")
379 (pop-option)
380 (setf noprint t))
381 ((string= option "--disable-debugger")
382 (pop-option)
383 (setf disable-debugger t))
384 ((string= option "--quit")
385 (pop-option)
386 (setf finally-quit t))
387 ((string= option "--non-interactive")
388 ;; This option is short for --quit and --disable-debugger,
389 ;; which are needed in combination for reliable non-
390 ;; interactive startup.
391 (pop-option)
392 (setf finally-quit t)
393 (setf disable-debugger t))
394 ((string= option "--end-toplevel-options")
395 (pop-option)
396 (return))
398 ;; Anything we don't recognize as a toplevel
399 ;; option must be the start of user-level
400 ;; options.. except that if we encounter
401 ;; "--end-toplevel-options" after we gave up
402 ;; because we didn't recognize an option as a
403 ;; toplevel option, then the option we gave up on
404 ;; must have been an error. (E.g. in
405 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
406 ;; this test will let us detect that the string
407 ;; "--eval(b)" is an error.)
408 (if (find "--end-toplevel-options" options
409 :test #'string=)
410 (startup-error "bad toplevel option: ~S"
411 (first options))
412 (return)))))))
413 (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
415 ;; Delete all the options that we processed, so that only
416 ;; user-level options are left visible to user code.
417 (when *posix-argv*
418 (setf (rest *posix-argv*) options))
420 ;; Disable debugger before processing initialization files & co.
421 (when disable-debugger
422 (disable-debugger))
424 ;; Handle initialization files.
425 (/show0 "handling initialization files in TOPLEVEL-INIT")
426 ;; This CATCH is needed for the debugger command TOPLEVEL to
427 ;; work.
428 (catch 'toplevel-catcher
429 ;; We wrap all the pre-REPL user/system customized startup
430 ;; code in a restart.
432 ;; (Why not wrap everything, even the stuff above, in this
433 ;; restart? Errors above here are basically command line
434 ;; or Unix environment errors, e.g. a missing file or a
435 ;; typo on the Unix command line, and you don't need to
436 ;; get into Lisp to debug them, you should just start over
437 ;; and do it right at the Unix level. Errors below here
438 ;; are generally errors in user Lisp code, and it might be
439 ;; helpful to let the user reach the REPL in order to help
440 ;; figure out what's going on.)
441 (restart-case
442 (flet ((process-init-file (kind specified-pathname default-function)
443 (awhen (or specified-pathname (funcall default-function))
444 (with-open-file (stream (if specified-pathname
445 (parse-native-namestring it)
446 (pathname it))
447 :if-does-not-exist nil)
448 (cond (stream
449 (dx-flet ((thunk ()
450 (load-as-source stream :context kind)))
451 (sb!fasl::call-with-load-bindings #'thunk stream)))
452 (specified-pathname
453 (cerror "Ignore missing init file"
454 "The specified ~A file ~A was not found."
455 kind specified-pathname)))))))
456 (unless no-sysinit
457 (process-init-file "sysinit" sysinit *sysinit-pathname-function*))
458 (unless no-userinit
459 (process-init-file "userinit" userinit *userinit-pathname-function*))
460 (when finally-quit
461 (push (list :quit) reversed-options))
462 (process-eval/load-options (nreverse reversed-options))
463 (when script
464 (process-script script)
465 (bug "PROCESS-SCRIPT returned")))
466 (abort ()
467 :report (lambda (s)
468 (write-string
469 (if script
470 ;; In case script calls (enable-debugger)!
471 "Abort script, exiting lisp."
472 "Skip to toplevel READ/EVAL/PRINT loop.")
474 (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
475 (values)) ; (no-op, just fall through)
476 (exit ()
477 :report "Exit SBCL (calling #'EXIT, killing the process)."
478 :test (lambda (c) (declare (ignore c)) (not script))
479 (/show0 "falling through to EXIT from pre-REPL RESTART-CASE")
480 (exit :code 1))))
482 ;; one more time for good measure, in case we fell out of the
483 ;; RESTART-CASE above before one of the flushes in the ordinary
484 ;; flow of control had a chance to operate
485 (flush-standard-output-streams)
487 (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
488 (toplevel-repl noprint)
489 ;; (classic CMU CL error message: "You're certainly a clever child.":-)
490 (critically-unreachable "after TOPLEVEL-REPL")))
492 ;;; hooks to support customized toplevels like ACL-style toplevel from
493 ;;; KMR on sbcl-devel 2002-12-21. Altered by CSR 2003-11-16 for
494 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
495 (defvar *repl-read-form-fun* #'repl-read-form-fun
496 "A function of two stream arguments IN and OUT for the toplevel REPL to
497 call: Return the next Lisp form to evaluate (possibly handling other magic --
498 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
499 stream is there to support magic which requires issuing new prompts.")
500 (defvar *repl-prompt-fun* #'repl-prompt-fun
501 "A function of one argument STREAM for the toplevel REPL to call: Prompt
502 the user for input.")
503 (defvar *repl-fun-generator* (constantly #'repl-fun)
504 "A function of no arguments returning a function of one argument NOPRINT
505 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
506 *STANDARD-OUTPUT* are set up.")
508 ;;; read-eval-print loop for the default system toplevel
509 (defun toplevel-repl (noprint)
510 (/show0 "entering TOPLEVEL-REPL")
511 (let ((* nil) (** nil) (*** nil)
512 (- nil)
513 (+ nil) (++ nil) (+++ nil)
514 (/// nil) (// nil) (/ nil))
515 (/show0 "about to funcall *REPL-FUN-GENERATOR*")
516 (let ((repl-fun (funcall *repl-fun-generator*)))
517 ;; Each REPL in a multithreaded world should have bindings of
518 ;; most CL specials (most critically *PACKAGE*).
519 (with-rebound-io-syntax
520 (handler-bind ((step-condition 'invoke-stepper))
521 (loop
522 (/show0 "about to set up restarts in TOPLEVEL-REPL")
523 ;; CLHS recommends that there should always be an
524 ;; ABORT restart; we have this one here, and one per
525 ;; debugger level.
526 (with-simple-restart
527 (abort "~@<Exit debugger, returning to top level.~@:>")
528 (catch 'toplevel-catcher
529 ;; In the event of a control-stack-exhausted-error, we
530 ;; should have unwound enough stack by the time we get
531 ;; here that this is now possible.
532 #!-win32
533 (sb!kernel::reset-control-stack-guard-page)
534 (funcall repl-fun noprint)
535 (critically-unreachable "after REPL")))))))))
537 ;;; Our default REPL prompt is the minimal traditional one.
538 (defun repl-prompt-fun (stream)
539 (fresh-line stream)
540 (write-string "* " stream)) ; arbitrary but customary REPL prompt
542 ;;; Our default form reader does relatively little magic, but does
543 ;;; handle the Unix-style EOF-is-end-of-process convention.
544 (defun repl-read-form-fun (in out)
545 (declare (type stream in out) (ignore out))
546 ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
547 ;; recovered from -- flip it here.
548 (when *read-suppress*
549 (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
550 (setf *read-suppress* nil))
551 (let* ((eof-marker (cons nil nil))
552 (form (read in nil eof-marker)))
553 (if (eq form eof-marker)
554 (exit)
555 form)))
557 (defun repl-fun (noprint)
558 (/show0 "entering REPL")
559 (loop
560 (unwind-protect
561 (progn
562 ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
563 (scrub-control-stack)
564 (sb!thread::get-foreground)
565 (unless noprint
566 (flush-standard-output-streams)
567 (funcall *repl-prompt-fun* *standard-output*)
568 ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
569 ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
570 ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
571 ;; odd. But maybe there *is* a valid reason in some
572 ;; circumstances? perhaps some deadlock issue when being driven
573 ;; by another process or something...)
574 (force-output *standard-output*))
575 (let* ((form (funcall *repl-read-form-fun*
576 *standard-input*
577 *standard-output*))
578 (results (multiple-value-list (interactive-eval form))))
579 (unless noprint
580 (dolist (result results)
581 (fresh-line)
582 (prin1 result)))))
583 ;; If we started stepping in the debugger we want to stop now.
584 (disable-stepping))))
586 ;;; a convenient way to get into the assembly-level debugger
587 (defun %halt ()
588 (%primitive sb!c:halt))