1.0.45.35: revert 1.0.45.30 due to regression (lp#677779)
[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   #!+hpux (defvar sb!vm::*c-lra*)
24   (defvar *free-interrupt-context-index*))
25 \f
26 ;;; specials initialized by !COLD-INIT
27
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                   *type-system-initialized*))
34
35 (defvar *cold-init-complete-p*)
36
37 ;;; counts of nested errors (with internal errors double-counted)
38 (defvar *maximum-error-depth*)
39 (defvar *current-error-depth*)
40
41 ;;;; default initfiles
42
43 (defun sysinit-pathname ()
44   (or (let ((sbcl-homedir (sbcl-homedir-pathname)))
45         (when sbcl-homedir
46           (probe-file (merge-pathnames "sbclrc" sbcl-homedir))))
47       #!+win32
48       (merge-pathnames "sbcl\\sbclrc"
49                        (sb!win32::get-folder-pathname
50                         sb!win32::csidl_common_appdata))
51       #!-win32
52       "/etc/sbclrc"))
53
54 (defun userinit-pathname ()
55   (merge-pathnames ".sbclrc" (user-homedir-pathname)))
56
57 (defvar *sysinit-pathname-function* #'sysinit-pathname
58   #!+sb-doc
59   "Designator for a function of zero arguments called to obtain a pathname
60 designator for the default sysinit file, or NIL. If the function returns NIL,
61 no sysinit file is used unless one has been specified on the command-line.")
62
63 (defvar *userinit-pathname-function* #'userinit-pathname
64   #!+sb-doc
65   "Designator for a function of zero arguments called to obtain a pathname
66 designator or a stream for the default userinit file, or NIL. If the function
67 returns NIL, no userinit file is used unless one has been specified on the
68 command-line.")
69
70 \f
71 ;;;; miscellaneous utilities for working with with TOPLEVEL
72
73 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
74 ;;; by QUIT) is caught and any final processing and return codes are
75 ;;; handled appropriately.
76 (defmacro handling-end-of-the-world (&body body)
77   (with-unique-names (caught)
78     `(let ((,caught (catch '%end-of-the-world
79                       (/show0 "inside CATCH '%END-OF-THE-WORLD")
80                       (unwind-protect
81                            (progn ,@body)
82                         (call-hooks "exit" *exit-hooks*)))))
83       (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
84       (flush-standard-output-streams)
85       (sb!thread::terminate-session)
86       (/show0 "calling UNIX-EXIT")
87       (sb!unix:unix-exit ,caught))))
88 \f
89 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
90
91 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
92 ;;; of hyperspace.
93 (defmacro infinite-error-protect (&rest forms)
94   `(unless (infinite-error-protector)
95      (/show0 "back from INFINITE-ERROR-PROTECTOR")
96      (let ((*current-error-depth* (1+ *current-error-depth*)))
97        (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
98        ;; arbitrary truncation
99        #!+sb-show (sb!debug:backtrace 8)
100        ,@forms)))
101
102 ;;; a helper function for INFINITE-ERROR-PROTECT
103 (defun infinite-error-protector ()
104   (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
105   (/hexstr *current-error-depth*)
106   (cond ((not *cold-init-complete-p*)
107          (%primitive print "Argh! error in cold init, halting")
108          (%primitive sb!c:halt))
109         ((or (not (boundp '*current-error-depth*))
110              (not (realp   *current-error-depth*))
111              (not (boundp '*maximum-error-depth*))
112              (not (realp   *maximum-error-depth*)))
113          (%primitive print "Argh! corrupted error depth, halting")
114          (%primitive sb!c:halt))
115         ((> *current-error-depth* *maximum-error-depth*)
116          (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
117          (/hexstr *maximum-error-depth*)
118          (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
119          (error-error "Help! "
120                       *current-error-depth*
121                       " nested errors. "
122                       "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
123          t)
124         (t
125          (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
126          nil)))
127
128 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
129 ;;; one point (shown below), and SBCL cross-compiled it without
130 ;;; warning about FORMS being undefined. Check whether that problem
131 ;;; (missing warning) is repeatable in the final system and if so, fix
132 ;;; it.
133 #|
134 (defun infinite-error-protector ()
135   `(cond ((not *cold-init-complete-p*)
136           (%primitive print "Argh! error in cold init, halting")
137           (%primitive sb!c:halt))
138          ((or (not (boundp '*current-error-depth*))
139               (not (realp   *current-error-depth*))
140               (not (boundp '*maximum-error-depth*))
141               (not (realp   *maximum-error-depth*)))
142           (%primitive print "Argh! corrupted error depth, halting")
143           (%primitive sb!c:halt))
144          ((> *current-error-depth* *maximum-error-depth*)
145           (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
146           (error-error "Help! "
147                        *current-error-depth*
148                        " nested errors. "
149                        "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
150           (progn ,@forms)
151           t)
152          (t
153           (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
154           nil)))
155 |#
156 \f
157 ;;;; miscellaneous external functions
158
159 (defun sleep (seconds)
160   #!+sb-doc
161   "This function causes execution to be suspended for SECONDS. SECONDS may be
162 any non-negative real number."
163   (when (or (not (realp seconds))
164             (minusp seconds))
165     (error 'simple-type-error
166            :format-control "invalid argument to SLEEP: ~S"
167            :format-arguments (list seconds)
168            :datum seconds
169            :expected-type '(real 0)))
170   #!-win32
171   (multiple-value-bind (sec nsec)
172       (if (integerp seconds)
173           (values seconds 0)
174           (multiple-value-bind (sec frac)
175               (truncate seconds)
176             (values sec (truncate frac 1e-9))))
177     ;; nanosleep() accepts time_t as the first argument, but on some platforms
178     ;; it is restricted to 100 million seconds. Maybe someone can actually
179     ;; have a reason to sleep for over 3 years?
180     (loop while (> sec (expt 10 8))
181           do (decf sec (expt 10 8))
182              (sb!unix:nanosleep (expt 10 8) 0))
183     (sb!unix:nanosleep sec nsec))
184   #!+win32
185   (sb!win32:millisleep (truncate (* seconds 1000)))
186   nil)
187 \f
188 ;;;; the default toplevel function
189
190 (defvar / nil
191   #!+sb-doc
192   "a list of all the values returned by the most recent top level EVAL")
193 (defvar //  nil #!+sb-doc "the previous value of /")
194 (defvar /// nil #!+sb-doc "the previous value of //")
195 (defvar *   nil #!+sb-doc "the value of the most recent top level EVAL")
196 (defvar **  nil #!+sb-doc "the previous value of *")
197 (defvar *** nil #!+sb-doc "the previous value of **")
198 (defvar +   nil #!+sb-doc "the value of the most recent top level READ")
199 (defvar ++  nil #!+sb-doc "the previous value of +")
200 (defvar +++ nil #!+sb-doc "the previous value of ++")
201 (defvar -   nil #!+sb-doc "the form currently being evaluated")
202
203 (defun interactive-eval (form &key (eval #'eval))
204   #!+sb-doc
205   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
206 +++, ++, +, ///, //, /, and -."
207   (setf - form)
208   (unwind-protect
209        (let ((results (multiple-value-list (funcall eval form))))
210          (setf /// //
211                // /
212                / results
213                *** **
214                ** *
215                * (car results)))
216     (setf +++ ++
217           ++ +
218           + -))
219   (unless (boundp '*)
220     ;; The bogon returned an unbound marker.
221     ;; FIXME: It would be safer to check every one of the values in RESULTS,
222     ;; instead of just the first one.
223     (setf * nil)
224     (cerror "Go on with * set to NIL."
225             "EVAL returned an unbound marker."))
226   (values-list /))
227
228 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
229 ;;; output streams before proceeding.
230 (defun flush-standard-output-streams ()
231   (dolist (name '(*debug-io*
232                   *error-output*
233                   *query-io*
234                   *standard-output*
235                   *trace-output*
236                   *terminal-io*))
237     ;; FINISH-OUTPUT may block more easily than FORCE-OUTPUT
238     (force-output (symbol-value name)))
239   (values))
240
241 (defun process-init-file (specified-pathname kind)
242   (multiple-value-bind (context default-function)
243       (ecase kind
244         (:system
245          (values "sysinit" *sysinit-pathname-function*))
246         (:user
247          (values "userinit" *userinit-pathname-function*)))
248     (flet ((process-stream (stream pathname)
249              (with-simple-restart (abort "Skip rest of ~A file ~S."
250                                          context (native-namestring pathname))
251                (loop
252                  (with-simple-restart
253                      (continue "Ignore error and continue processing ~A file ~S."
254                                context (native-namestring pathname))
255                    (let ((form (read stream nil stream)))
256                      (if (eq stream form)
257                          (return-from process-init-file nil)
258                          (eval form))))))))
259       (if specified-pathname
260           (with-open-file (stream (parse-native-namestring specified-pathname)
261                                   :if-does-not-exist nil)
262             (if stream
263                 (process-stream stream (pathname stream))
264                 (cerror "Ignore missing init file"
265                         "The specified ~A file ~A was not found."
266                         context specified-pathname)))
267           (let ((default (funcall default-function)))
268             (when default
269               (with-open-file (stream (pathname default) :if-does-not-exist nil)
270                 (when stream
271                   (process-stream stream (pathname stream))))))))))
272
273 (defun process-eval/load-options (options)
274   (/show0 "handling --eval and --load options")
275   (flet ((process-1 (cons)
276            (destructuring-bind (opt . value) cons
277              (ecase opt
278                (:eval
279                 (with-simple-restart (continue "Ignore runtime option --eval ~S."
280                                                value)
281                   (multiple-value-bind (expr pos) (read-from-string value)
282                     (if (eq value (read-from-string value nil value :start pos))
283                         (eval expr)
284                         (error "Multiple expressions in --eval option: ~S"
285                                value)))))
286                (:load
287                 (with-simple-restart (continue "Ignore runtime option --load ~S."
288                                                value)
289                   (load (native-pathname value))))))
290            (flush-standard-output-streams)))
291     (with-simple-restart (abort "Skip rest of --eval and --load options.")
292       (dolist (option options)
293         (process-1 option)))))
294
295 (defun process-script (script)
296   (let ((pathname (native-pathname script)))
297     (handling-end-of-the-world
298       (with-open-file (f pathname :element-type :default)
299         (sb!fasl::maybe-skip-shebang-line f)
300         (load f :verbose nil :print nil)
301         (quit)))))
302
303 ;; Errors while processing the command line cause the system to QUIT,
304 ;; instead of trying to go into the Lisp debugger, because trying to
305 ;; go into the Lisp debugger would get into various annoying issues of
306 ;; where we should go after the user tries to return from the
307 ;; debugger.
308 (defun startup-error (control-string &rest args)
309   (format *error-output*
310           "fatal error before reaching READ-EVAL-PRINT loop: ~%  ~?~%"
311           control-string
312           args)
313   (quit :unix-status 1))
314
315 ;;; the default system top level function
316 (defun toplevel-init ()
317   (/show0 "entering TOPLEVEL-INIT")
318   (let ( ;; value of --sysinit option
319         (sysinit nil)
320         ;; t if --no-sysinit option given
321         (no-sysinit nil)
322         ;; value of --userinit option
323         (userinit nil)
324         ;; t if --no-userinit option given
325         (no-userinit nil)
326         ;; t if --disable-debugger option given
327         (disable-debugger nil)
328         ;; list of (<kind> . <string>) conses representing --eval and --load
329         ;; options. options. --eval options are stored as strings, so that
330         ;; they can be passed to READ only after their predecessors have been
331         ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
332         ;; creates a package referred to in the next EVAL form. Storing the
333         ;; original string also makes for easier debugging.
334         (reversed-options nil)
335         ;; Has a --noprint option been seen?
336         (noprint nil)
337         ;; Has a --script option been seen?
338         (script nil)
339         ;; everything in *POSIX-ARGV* except for argv[0]=programname
340         (options (rest *posix-argv*)))
341
342     (declare (type list options))
343
344     (/show0 "done with outer LET in TOPLEVEL-INIT")
345
346     ;; FIXME: There are lots of ways for errors to happen around here
347     ;; (e.g. bad command line syntax, or READ-ERROR while trying to
348     ;; READ an --eval string). Make sure that they're handled
349     ;; reasonably.
350
351     ;; Process command line options.
352     (loop while options do
353          (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
354          (let ((option (first options)))
355            (flet ((pop-option ()
356                     (if options
357                         (pop options)
358                         (startup-error
359                          "unexpected end of command line options"))))
360              (cond ((string= option "--script")
361                     (pop-option)
362                     (setf disable-debugger t
363                           no-userinit t
364                           no-sysinit t
365                           script (pop-option))
366                     (return))
367                    ((string= option "--sysinit")
368                     (pop-option)
369                     (if sysinit
370                         (startup-error "multiple --sysinit options")
371                         (setf sysinit (pop-option))))
372                    ((string= option "--no-sysinit")
373                     (pop-option)
374                     (setf no-sysinit t))
375                    ((string= option "--userinit")
376                     (pop-option)
377                     (if userinit
378                         (startup-error "multiple --userinit options")
379                         (setf userinit (pop-option))))
380                    ((string= option "--no-userinit")
381                     (pop-option)
382                     (setf no-userinit t))
383                    ((string= option "--eval")
384                     (pop-option)
385                     (push (cons :eval (pop-option)) reversed-options))
386                    ((string= option "--load")
387                     (pop-option)
388                     (push (cons :load (pop-option)) reversed-options))
389                    ((string= option "--noprint")
390                     (pop-option)
391                     (setf noprint t))
392                    ((string= option "--disable-debugger")
393                     (pop-option)
394                     (setf disable-debugger t))
395                    ((string= option "--end-toplevel-options")
396                     (pop-option)
397                     (return))
398                    (t
399                     ;; Anything we don't recognize as a toplevel
400                     ;; option must be the start of user-level
401                     ;; options.. except that if we encounter
402                     ;; "--end-toplevel-options" after we gave up
403                     ;; because we didn't recognize an option as a
404                     ;; toplevel option, then the option we gave up on
405                     ;; must have been an error. (E.g. in
406                     ;;  "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
407                     ;; this test will let us detect that the string
408                     ;; "--eval(b)" is an error.)
409                     (if (find "--end-toplevel-options" options
410                               :test #'string=)
411                         (startup-error "bad toplevel option: ~S"
412                                        (first options))
413                         (return)))))))
414     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
415
416     ;; Delete all the options that we processed, so that only
417     ;; user-level options are left visible to user code.
418     (setf (rest *posix-argv*) options)
419
420     ;; Disable debugger before processing initialization files & co.
421     (when disable-debugger
422       (sb!ext:disable-debugger))
423
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.
431       ;;
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           (progn
443             (unless no-sysinit
444               (process-init-file sysinit :system))
445             (unless no-userinit
446               (process-init-file userinit :user))
447             (process-eval/load-options (nreverse reversed-options))
448             (when script
449               (process-script script)
450               (bug "PROCESS-SCRIPT returned")))
451         (abort ()
452           :report (lambda (s)
453                     (write-string
454                      (if script
455                          ;; In case script calls (enable-debugger)!
456                          "Abort script, exiting lisp."
457                          "Skip to toplevel READ/EVAL/PRINT loop.")
458                      s))
459           (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
460           (values))                     ; (no-op, just fall through)
461         (quit ()
462           :report "Quit SBCL (calling #'QUIT, killing the process)."
463           :test (lambda (c) (declare (ignore c)) (not script))
464           (/show0 "falling through to QUIT from pre-REPL RESTART-CASE")
465           (quit :unix-status 1))))
466
467     ;; one more time for good measure, in case we fell out of the
468     ;; RESTART-CASE above before one of the flushes in the ordinary
469     ;; flow of control had a chance to operate
470     (flush-standard-output-streams)
471
472     (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
473     (toplevel-repl noprint)
474     ;; (classic CMU CL error message: "You're certainly a clever child.":-)
475     (critically-unreachable "after TOPLEVEL-REPL")))
476
477 ;;; hooks to support customized toplevels like ACL-style toplevel from
478 ;;; KMR on sbcl-devel 2002-12-21.  Altered by CSR 2003-11-16 for
479 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
480 (defvar *repl-read-form-fun* #'repl-read-form-fun
481   #!+sb-doc
482   "A function of two stream arguments IN and OUT for the toplevel REPL to
483 call: Return the next Lisp form to evaluate (possibly handling other magic --
484 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
485 stream is there to support magic which requires issuing new prompts.")
486 (defvar *repl-prompt-fun* #'repl-prompt-fun
487   #!+sb-doc
488   "A function of one argument STREAM for the toplevel REPL to call: Prompt
489 the user for input.")
490 (defvar *repl-fun-generator* (constantly #'repl-fun)
491   #!+sb-doc
492   "A function of no arguments returning a function of one argument NOPRINT
493 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
494 *STANDARD-OUTPUT* are set up.")
495
496 ;;; read-eval-print loop for the default system toplevel
497 (defun toplevel-repl (noprint)
498   (/show0 "entering TOPLEVEL-REPL")
499   (let ((* nil) (** nil) (*** nil)
500         (- nil)
501         (+ nil) (++ nil) (+++ nil)
502         (/// nil) (// nil) (/ nil))
503     (/show0 "about to funcall *REPL-FUN-GENERATOR*")
504     (let ((repl-fun (funcall *repl-fun-generator*)))
505       ;; Each REPL in a multithreaded world should have bindings of
506       ;; most CL specials (most critically *PACKAGE*).
507       (with-rebound-io-syntax
508           (handler-bind ((step-condition 'invoke-stepper))
509             (loop
510                (/show0 "about to set up restarts in TOPLEVEL-REPL")
511                ;; CLHS recommends that there should always be an
512                ;; ABORT restart; we have this one here, and one per
513                ;; debugger level.
514                (with-simple-restart
515                    (abort "~@<Exit debugger, returning to top level.~@:>")
516                  (catch 'toplevel-catcher
517                    ;; In the event of a control-stack-exhausted-error, we
518                    ;; should have unwound enough stack by the time we get
519                    ;; here that this is now possible.
520                    #!-win32
521                    (sb!kernel::reset-control-stack-guard-page)
522                    (funcall repl-fun noprint)
523                    (critically-unreachable "after REPL")))))))))
524
525 ;;; Our default REPL prompt is the minimal traditional one.
526 (defun repl-prompt-fun (stream)
527   (fresh-line stream)
528   (write-string "* " stream)) ; arbitrary but customary REPL prompt
529
530 ;;; Our default form reader does relatively little magic, but does
531 ;;; handle the Unix-style EOF-is-end-of-process convention.
532 (defun repl-read-form-fun (in out)
533   (declare (type stream in out) (ignore out))
534   ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
535   ;; recovered from -- flip it here.
536   (when *read-suppress*
537     (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
538     (setf *read-suppress* nil))
539   (let* ((eof-marker (cons nil nil))
540          (form (read in nil eof-marker)))
541     (if (eq form eof-marker)
542         (quit)
543         form)))
544
545 (defun repl-fun (noprint)
546   (/show0 "entering REPL")
547   (loop
548    (unwind-protect
549         (progn
550           ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
551           (scrub-control-stack)
552           (sb!thread::get-foreground)
553           (unless noprint
554             (flush-standard-output-streams)
555             (funcall *repl-prompt-fun* *standard-output*)
556             ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
557             ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
558             ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
559             ;; odd. But maybe there *is* a valid reason in some
560             ;; circumstances? perhaps some deadlock issue when being driven
561             ;; by another process or something...)
562             (force-output *standard-output*))
563           (let* ((form (funcall *repl-read-form-fun*
564                                 *standard-input*
565                                 *standard-output*))
566                  (results (multiple-value-list (interactive-eval form))))
567             (unless noprint
568               (dolist (result results)
569                 (fresh-line)
570                 (prin1 result)))))
571      ;; If we started stepping in the debugger we want to stop now.
572      (disable-stepping))))
573 \f
574 ;;; a convenient way to get into the assembly-level debugger
575 (defun %halt ()
576   (%primitive sb!c:halt))