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