0.pre7.49:
[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 (defconstant most-positive-fixnum #.sb!vm:*target-most-positive-fixnum*
17   #!+sb-doc
18   "the fixnum closest in value to positive infinity")
19
20 (defconstant most-negative-fixnum #.sb!vm:*target-most-negative-fixnum*
21   #!+sb-doc
22   "the fixnum closest in value to negative infinity")
23 \f
24 ;;;; magic specials initialized by GENESIS
25
26 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
27 ;;; of all static symbols in early-impl.lisp.
28 (progn
29   (defvar *current-catch-block*)
30   (defvar *current-unwind-protect-block*)
31   (defvar *free-interrupt-context-index*))
32 \f
33 ;;; specials initialized by !COLD-INIT
34
35 ;;; FIXME: These could be converted to DEFVARs.
36 (declaim (special *gc-inhibit* *already-maybe-gcing*
37                   *need-to-collect-garbage*
38                   *gc-notify-stream*
39                   *before-gc-hooks* *after-gc-hooks*
40                   #!+x86 *pseudo-atomic-atomic*
41                   #!+x86 *pseudo-atomic-interrupted*
42                   sb!unix::*interrupts-enabled*
43                   sb!unix::*interrupt-pending*
44                   *type-system-initialized*))
45
46 (defvar *cold-init-complete-p*)
47
48 ;;; counts of nested errors (with internal errors double-counted)
49 (defvar *maximum-error-depth*)
50 (defvar *current-error-depth*)
51 \f
52 ;;;; miscellaneous utilities for working with with TOPLEVEL
53
54 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
55 ;;; by QUIT) is caught and any final processing and return codes are
56 ;;; handled appropriately.
57 (defmacro handling-end-of-the-world (&body body)
58   (let ((caught (gensym "CAUGHT")))
59     `(let ((,caught (catch '%end-of-the-world
60                       (/show0 "inside CATCH '%END-OF-THE-WORLD")
61                       ,@body)))
62        (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
63        (flush-standard-output-streams)
64        (/show0 "calling UNIX-EXIT")
65        (sb!unix:unix-exit ,caught))))
66 \f
67 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
68
69 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
70 ;;; of hyperspace.
71 (defmacro infinite-error-protect (&rest forms)
72   `(unless (infinite-error-protector)
73      (/show0 "back from INFINITE-ERROR-PROTECTOR")
74      (let ((*current-error-depth* (1+ *current-error-depth*)))
75        (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
76        #+sb-show (sb-debug:backtrace)
77        ,@forms)))
78
79 ;;; a helper function for INFINITE-ERROR-PROTECT
80 (defun infinite-error-protector ()
81   (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
82   (/hexstr *current-error-depth*)
83   (cond ((not *cold-init-complete-p*)
84          (%primitive print "Argh! error in cold init, halting")
85          (%primitive sb!c:halt))
86         ((or (not (boundp '*current-error-depth*))
87              (not (realp   *current-error-depth*))
88              (not (boundp '*maximum-error-depth*))
89              (not (realp   *maximum-error-depth*)))
90          (%primitive print "Argh! corrupted error depth, halting")
91          (%primitive sb!c:halt))
92         ((> *current-error-depth* *maximum-error-depth*)
93          (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
94          (/hexstr *maximum-error-depth*)
95          (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
96          (error-error "Help! "
97                       *current-error-depth*
98                       " nested errors. "
99                       "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
100          t)
101         (t
102          (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
103          nil)))
104
105 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
106 ;;; one point (shown below), and SBCL cross-compiled it without
107 ;;; warning about FORMS being undefined. Check whether that problem
108 ;;; (missing warning) is repeatable in the final system and if so, fix
109 ;;; it.
110 #|
111 (defun infinite-error-protector ()
112   `(cond ((not *cold-init-complete-p*)
113           (%primitive print "Argh! error in cold init, halting")
114           (%primitive sb!c:halt))
115          ((or (not (boundp '*current-error-depth*))
116               (not (realp   *current-error-depth*))
117               (not (boundp '*maximum-error-depth*))
118               (not (realp   *maximum-error-depth*)))
119           (%primitive print "Argh! corrupted error depth, halting")
120           (%primitive sb!c:halt))
121          ((> *current-error-depth* *maximum-error-depth*)
122           (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
123           (error-error "Help! "
124                        *current-error-depth*
125                        " nested errors. "
126                        "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
127           (progn ,@forms)
128           t)
129          (t
130           (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
131           nil)))
132 |#
133 \f
134 ;;;; miscellaneous external functions
135
136 #!-mp ; The multi-processing version is defined in multi-proc.lisp.
137 (defun sleep (n)
138   #!+sb-doc
139   "This function causes execution to be suspended for N seconds. N may
140   be any non-negative, non-complex number."
141   (when (or (not (realp n))
142             (minusp n))
143     (error "Invalid argument to SLEEP: ~S.~%~
144             Must be a non-negative, non-complex number."
145            n))
146   (multiple-value-bind (sec usec)
147       (if (integerp n)
148           (values n 0)
149           (multiple-value-bind (sec frac)
150               (truncate n)
151             (values sec(truncate frac 1e-6))))
152     (sb!unix:unix-select 0 0 0 0 sec usec))
153   nil)
154 \f
155 ;;;; SCRUB-CONTROL-STACK
156
157 (defconstant bytes-per-scrub-unit 2048)
158
159 ;;; Zero the unused portion of the control stack so that old objects
160 ;;; are not kept alive because of uninitialized stack variables.
161 ;;;
162 ;;; FIXME: Why do we need to do this instead of just letting GC read
163 ;;; the stack pointer and avoid messing with the unused portion of
164 ;;; the control stack? (Is this a multithreading thing where there's
165 ;;; one control stack and stack pointer per thread, and it might not
166 ;;; be easy to tell what a thread's stack pointer value is when
167 ;;; looking in from another thread?)
168 (defun scrub-control-stack ()
169   (declare (optimize (speed 3) (safety 0))
170            (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
171
172   #!-x86 ; machines where stack grows upwards (I guess) -- WHN 19990906
173   (labels
174       ((scrub (ptr offset count)
175          (declare (type system-area-pointer ptr)
176                   (type (unsigned-byte 16) offset)
177                   (type (unsigned-byte 20) count)
178                   (values (unsigned-byte 20)))
179          (cond ((= offset bytes-per-scrub-unit)
180                 (look (sap+ ptr bytes-per-scrub-unit) 0 count))
181                (t
182                 (setf (sap-ref-32 ptr offset) 0)
183                 (scrub ptr (+ offset sb!vm:word-bytes) count))))
184        (look (ptr offset count)
185          (declare (type system-area-pointer ptr)
186                   (type (unsigned-byte 16) offset)
187                   (type (unsigned-byte 20) count)
188                   (values (unsigned-byte 20)))
189          (cond ((= offset bytes-per-scrub-unit)
190                 count)
191                ((zerop (sap-ref-32 ptr offset))
192                 (look ptr (+ offset sb!vm:word-bytes) count))
193                (t
194                 (scrub ptr offset (+ count sb!vm:word-bytes))))))
195     (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
196            (initial-offset (logand csp (1- bytes-per-scrub-unit))))
197       (declare (type (unsigned-byte 32) csp))
198       (scrub (int-sap (- csp initial-offset))
199              (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
200              0)))
201
202   #!+x86 ;; (Stack grows downwards.)
203   (labels
204       ((scrub (ptr offset count)
205          (declare (type system-area-pointer ptr)
206                   (type (unsigned-byte 16) offset)
207                   (type (unsigned-byte 20) count)
208                   (values (unsigned-byte 20)))
209          (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:word-bytes)))))
210            (cond ((= offset bytes-per-scrub-unit)
211                   (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
212                         0 count))
213                  (t ;; need to fix bug in %SET-STACK-REF
214                   (setf (sap-ref-32 loc 0) 0)
215                   (scrub ptr (+ offset sb!vm:word-bytes) count)))))
216        (look (ptr offset count)
217          (declare (type system-area-pointer ptr)
218                   (type (unsigned-byte 16) offset)
219                   (type (unsigned-byte 20) count)
220                   (values (unsigned-byte 20)))
221          (let ((loc (int-sap (- (sap-int ptr) offset))))
222            (cond ((= offset bytes-per-scrub-unit)
223                   count)
224                  ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
225                   (look ptr (+ offset sb!vm:word-bytes) count))
226                  (t
227                   (scrub ptr offset (+ count sb!vm:word-bytes)))))))
228     (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
229            (initial-offset (logand csp (1- bytes-per-scrub-unit))))
230       (declare (type (unsigned-byte 32) csp))
231       (scrub (int-sap (+ csp initial-offset))
232              (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
233              0))))
234 \f
235 ;;;; the default toplevel function
236
237 (defvar / nil
238   #!+sb-doc
239   "a list of all the values returned by the most recent top-level EVAL")
240 (defvar //  nil #!+sb-doc "the previous value of /")
241 (defvar /// nil #!+sb-doc "the previous value of //")
242 (defvar *   nil #!+sb-doc "the value of the most recent top-level EVAL")
243 (defvar **  nil #!+sb-doc "the previous value of *")
244 (defvar *** nil #!+sb-doc "the previous value of **")
245 (defvar +   nil #!+sb-doc "the value of the most recent top-level READ")
246 (defvar ++  nil #!+sb-doc "the previous value of +")
247 (defvar +++ nil #!+sb-doc "the previous value of ++")
248 (defvar -   nil #!+sb-doc "the form currently being evaluated")
249 (defvar *prompt* "* "
250   #!+sb-doc
251   "The top-level prompt string. This also may be a function of no arguments
252    that returns a simple-string.")
253
254 (defun interactive-eval (form)
255   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
256    +++, ++, +, ///, //, /, and -."
257   (setf - form)
258   (let ((results (multiple-value-list (eval form))))
259     (setf /// //
260           // /
261           / results
262           *** **
263           ** *
264           * (car results)))
265   (setf +++ ++
266         ++ +
267         + -)
268   (unless (boundp '*)
269     ;; The bogon returned an unbound marker.
270     ;; FIXME: It would be safer to check every one of the values in RESULTS,
271     ;; instead of just the first one.
272     (setf * nil)
273     (cerror "Go on with * set to NIL."
274             "EVAL returned an unbound marker."))
275   (values-list /))
276
277 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
278 ;;; output streams before proceeding.
279 (defun flush-standard-output-streams ()
280   (dolist (name '(*debug-io*
281                   *error-output*
282                   *query-io*
283                   *standard-output*
284                   *trace-output*))
285     (finish-output (symbol-value name)))
286   (values))
287
288 ;;; the default system top-level function
289 (defun toplevel-init ()
290
291   (/show0 "entering TOPLEVEL-INIT")
292   
293   (let ((sysinit nil)        ; value of --sysinit option
294         (userinit nil)       ; value of --userinit option
295         (reversed-evals nil) ; values of --eval options, in reverse order
296         (noprint nil)        ; Has a --noprint option been seen?
297         (noprogrammer nil)   ; Has a --noprogammer option been seen?
298         (options (rest *posix-argv*))) ; skipping program name
299
300     (/show0 "done with outer LET in TOPLEVEL-INIT")
301   
302     ;; FIXME: There are lots of ways for errors to happen around here
303     ;; (e.g. bad command line syntax, or READ-ERROR while trying to
304     ;; READ an --eval string). Make sure that they're handled
305     ;; reasonably. Also, perhaps all errors while parsing the command
306     ;; line should cause the system to QUIT, instead of trying to go
307     ;; into the Lisp debugger.
308     
309     ;; Parse command line options.
310     (loop while options do
311           (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
312           (let ((option (first options)))
313             (flet ((pop-option ()
314                      (if options
315                          (pop options)
316                          (error "unexpected end of command line options"))))
317               (cond ((string= option "--sysinit")
318                      (pop-option)
319                      (if sysinit
320                          (error "multiple --sysinit options")
321                          (setf sysinit (pop-option))))
322                     ((string= option "--userinit")
323                      (pop-option)
324                      (if userinit
325                          (error "multiple --userinit options")
326                          (setf userinit (pop-option))))
327                     ((string= option "--eval")
328                      (pop-option)
329                      (let ((eval-as-string (pop-option)))
330                        (with-input-from-string (eval-stream eval-as-string)
331                          (let* ((eof-marker (cons :eof :eof))
332                                 (eval (read eval-stream nil eof-marker))
333                                 (eof (read eval-stream nil eof-marker)))
334                            (cond ((eq eval eof-marker)
335                                   (error "unable to parse ~S"
336                                          eval-as-string))
337                                  ((not (eq eof eof-marker))
338                                   (error "more than one expression in ~S"
339                                          eval-as-string))
340                                  (t
341                                   (push eval reversed-evals)))))))
342                     ((string= option "--noprint")
343                      (pop-option)
344                      (setf noprint t))
345                     ((string= option "--noprogrammer")
346                      (pop-option)
347                      (setf noprogrammer t))
348                     ((string= option "--end-toplevel-options")
349                      (pop-option)
350                      (return))
351                     (t
352                      ;; Anything we don't recognize as a toplevel
353                      ;; option must be the start of user-level
354                      ;; options.. except that if we encounter
355                      ;; "--end-toplevel-options" after we gave up
356                      ;; because we didn't recognize an option as a
357                      ;; toplevel option, then the option we gave up on
358                      ;; must have been an error. (E.g. in
359                      ;;  "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
360                      ;; this test will let us detect that the string
361                      ;; "--eval(b)" is an error.)
362                      (if (find "--end-toplevel-options" options
363                                :test #'string=)
364                          (error "bad toplevel option: ~S" (first options))
365                          (return)))))))
366     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
367
368     ;; Excise all the options that we processed, so that only
369     ;; user-level options are left visible to user code.
370     (setf (rest *posix-argv*) options)
371
372     ;; Handle --noprogrammer option. We intentionally do this
373     ;; early so that it will affect the handling of initialization
374     ;; files and --eval options.
375     (/show0 "handling --noprogrammer option in TOPLEVEL-INIT")
376     (when noprogrammer
377       (setf *debugger-hook* 'noprogrammer-debugger-hook-fun
378             *debug-io* *error-output*))
379
380     ;; FIXME: Verify that errors in init files and/or --eval operations
381     ;; lead to reasonable behavior.
382
383     ;; Handle initialization files.
384     (/show0 "handling initialization files in TOPLEVEL-INIT")
385     (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
386            ;; return its truename.
387            (probe-init-files (&rest possible-init-file-names)
388              (/show0 "entering PROBE-INIT-FILES")
389              (prog1
390                  (find-if (lambda (x)
391                             (and (stringp x) (probe-file x)))
392                           possible-init-file-names)
393                (/show0 "leaving PROBE-INIT-FILES"))))
394       (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
395              (sysinit-truename (if sbcl-home
396                                    (probe-init-files sysinit
397                                                      (concatenate
398                                                       'string
399                                                       sbcl-home
400                                                       "/sbclrc"))
401                                    (probe-init-files sysinit
402                                                      "/etc/sbclrc"
403                                                      "/usr/local/etc/sbclrc")))
404              (user-home (or (posix-getenv "HOME")
405                             (error "The HOME environment variable is unbound, ~
406                                     so user init file can't be found.")))
407              (userinit-truename (probe-init-files userinit
408                                                   (concatenate
409                                                    'string
410                                                    user-home
411                                                    "/.sbclrc"))))
412         (/show0 "assigned SYSINIT-TRUENAME and USERINIT-TRUENAME")
413
414
415         ;; We wrap all the pre-REPL user/system customized startup code 
416         ;; in a restart.
417         ;;
418         ;; (Why not wrap everything, even the stuff above, in this
419         ;; restart? Errors above here are basically command line or
420         ;; Unix environment errors, e.g. a missing file or a typo on
421         ;; the Unix command line, and you don't need to get into Lisp
422         ;; to debug them, you should just start over and do it right
423         ;; at the Unix level. Errors below here are usually errors in
424         ;; user Lisp code, and it might be helpful to let the user
425         ;; reach the REPL in order to help figure out what's going on.)
426         (restart-case
427             (flet ((process-init-file (truename)
428                      (when truename
429                        (unless (load truename)
430                          (error "~S was not successfully loaded." truename))
431                        (flush-standard-output-streams))))
432               (process-init-file sysinit-truename)
433               (process-init-file userinit-truename)
434
435               ;; Process --eval options.
436               (/show0 "handling --eval options in TOPLEVEL-INIT")
437               (dolist (eval (reverse reversed-evals))
438                 (/show0 "handling one --eval option in TOPLEVEL-INIT")
439                 (eval eval)
440                 (flush-standard-output-streams)))
441           (continue ()
442                     :report "Continue anyway (skipping to toplevel read/eval/print loop)."
443                     (values)) ; (no-op, just fall through)
444           (quit ()
445                 :report "Quit SBCL (calling #'QUIT, killing the process)."
446                 (quit))))
447
448       ;; one more time for good measure, in case we fell out of the
449       ;; RESTART-CASE above before one of the flushes in the ordinary
450       ;; flow of control had a chance to operate
451       (flush-standard-output-streams)
452
453       (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
454       (toplevel-repl noprint))))
455
456 ;;; read-eval-print loop for the default system toplevel
457 (defun toplevel-repl (noprint)
458   (/show0 "entering TOPLEVEL-REPL")
459   (let ((* nil) (** nil) (*** nil)
460         (- nil)
461         (+ nil) (++ nil) (+++ nil)
462         (/// nil) (// nil) (/ nil)
463         (eof-marker (cons :eof nil)))
464     (loop
465       (/show0 "at head of outer LOOP in TOPLEVEL-REPL")
466       ;; There should only be one TOPLEVEL restart, and it's here, so
467       ;; restarting at TOPLEVEL always bounces you all the way out here.
468       (with-simple-restart (toplevel
469                             "Restart at toplevel READ/EVAL/PRINT loop.")
470         ;; We add a new ABORT restart for every debugger level, so 
471         ;; restarting at ABORT in a nested debugger gets you out to the
472         ;; innermost enclosing debugger, and only when you're in the
473         ;; outermost, unnested debugger level does restarting at ABORT 
474         ;; get you out to here.
475         (with-simple-restart (abort
476                               "Reduce debugger level (leaving debugger).")
477           (catch 'top-level-catcher
478           (sb!unix:unix-sigsetmask 0)   ; FIXME: What is this for?
479           (/show0 "about to enter inner LOOP in TOPLEVEL-REPL")
480           (loop                         ; FIXME: Do we need this inner LOOP?
481            ;; FIXME: It seems bad to have GC behavior depend on scrubbing
482            ;; the control stack before each interactive command. Isn't
483            ;; there some way we can convince the GC to just ignore
484            ;; dead areas of the control stack, so that we don't need to
485            ;; rely on this half-measure?
486            (scrub-control-stack)
487            (unless noprint
488              (fresh-line)
489              (princ (if (functionp *prompt*)
490                         (funcall *prompt*)
491                         *prompt*))
492              (flush-standard-output-streams))
493            (let ((form (read *standard-input* nil eof-marker)))
494              (if (eq form eof-marker)
495                  (quit)
496                  (let ((results
497                         (multiple-value-list (interactive-eval form))))
498                    (unless noprint
499                      (dolist (result results)
500                        (fresh-line)
501                        (prin1 result)))))))))))))
502
503 (defun noprogrammer-debugger-hook-fun (condition old-debugger-hook)
504   (declare (ignore old-debugger-hook))
505   (flet ((failure-quit (&key recklessly-p)
506            (quit :unix-status 1 :recklessly-p recklessly-p)))
507     ;; This HANDLER-CASE is here mostly to stop output immediately
508     ;; (and fall through to QUIT) when there's an I/O error. Thus,
509     ;; when we're run under a shell script or something, we can die
510     ;; cleanly when the script dies (and our pipes are cut), instead
511     ;; of falling into ldb or something messy like that.
512     (handler-case
513         (progn
514           (format *error-output*
515                   "~@<unhandled condition (of type ~S): ~2I~_~A~:>~2%"
516                   (type-of condition)
517                   condition)
518           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
519           ;; even if we hit an error within BACKTRACE we'll at least
520           ;; have the CONDITION printed out before we die.
521           (finish-output *error-output*)
522           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
523           ;; it seems as though we should at least truncate it somewhere.)
524           (sb!debug:backtrace 128 *error-output*)
525           (format *error-output*
526                   "~%unhandled condition in --noprogrammer mode, quitting~%")
527           (finish-output *error-output*)
528           (failure-quit))
529       (condition ()
530         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
531         ;; fail when our output streams are blown away, as e.g. when
532         ;; we're running under a Unix shell script and it dies somehow
533         ;; (e.g. because of a SIGINT). In that case, we might as well
534         ;; just give it up for a bad job, and stop trying to notify
535         ;; the user of anything.
536         ;;
537         ;; Actually, the only way I've run across to exercise the
538         ;; problem is to have more than one layer of shell script.
539         ;; I have a shell script which does
540         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
541         ;; and the problem occurs when I interrupt this with Ctrl-C
542         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
543         ;; I haven't figured out whether it's bash, time, tee, Linux, or
544         ;; what that is responsible, but that it's possible at all
545         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
546         (ignore-errors
547          (%primitive print "Argh! error within --noprogrammer error handling"))
548         (failure-quit :recklessly-p t)))))
549 \f
550 ;;; a convenient way to get into the assembly-level debugger
551 (defun %halt ()
552   (%primitive sb!c:halt))