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