cd1c923d4ca07ca91585423f3209dd3782d6cc75
[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 #!-gengc
27 (progn
28   (defvar *current-catch-block*)
29   (defvar *current-unwind-protect-block*)
30   (defvar *free-interrupt-context-index*))
31 \f
32 ;;; specials initialized by !COLD-INIT
33
34 ;;; FIXME: These could be converted to DEFVARs, and the stuff shared
35 ;;; in both #!+GENGC and #!-GENGC (actually everything in #!+GENGC)
36 ;;; could be made non-conditional.
37 (declaim
38   #!-gengc
39   (special *gc-inhibit* *already-maybe-gcing*
40            *need-to-collect-garbage*
41            *gc-notify-stream*
42            *before-gc-hooks* *after-gc-hooks*
43            #!+x86 *pseudo-atomic-atomic*
44            #!+x86 *pseudo-atomic-interrupted*
45            sb!unix::*interrupts-enabled*
46            sb!unix::*interrupt-pending*
47            *type-system-initialized*)
48   #!+gengc
49   (special *before-gc-hooks* *after-gc-hooks*
50            *gc-notify-stream*
51            *type-system-initialized*))
52
53 (defvar *cold-init-complete-p*)
54
55 ;;; counts of nested errors (with internal errors double-counted)
56 (defvar *maximum-error-depth*)
57 (defvar *current-error-depth*)
58 \f
59 ;;;; miscellaneous utilities for working with with TOPLEVEL
60
61 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
62 ;;; by QUIT) is caught and any final processing and return codes are
63 ;;; handled appropriately.
64 (defmacro handling-end-of-the-world (&body body)
65   (let ((caught (gensym "CAUGHT")))
66     `(let ((,caught (catch '%end-of-the-world
67                       (/show0 "inside CATCH '%END-OF-THE-WORLD")
68                       ,@body)))
69        (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
70        (flush-standard-output-streams)
71        (/show0 "calling UNIX-EXIT")
72        (sb!unix:unix-exit ,caught))))
73 \f
74 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
75
76 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out of
77 ;;; hyperspace.
78 (defmacro infinite-error-protect (&rest forms)
79   `(unless (infinite-error-protector)
80      (let ((*current-error-depth* (1+ *current-error-depth*)))
81        ,@forms)))
82
83 ;;; a helper function for INFINITE-ERROR-PROTECT
84 (defun infinite-error-protector ()
85   (cond ((not *cold-init-complete-p*)
86          (%primitive print "Argh! error in cold init, halting")
87          (%primitive sb!c:halt))
88         ((or (not (boundp '*current-error-depth*))
89              (not (realp   *current-error-depth*))
90              (not (boundp '*maximum-error-depth*))
91              (not (realp   *maximum-error-depth*)))
92          (%primitive print "Argh! corrupted error depth, halting")
93          (%primitive sb!c:halt))
94         ((> *current-error-depth* *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          nil)))
103
104 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
105 ;;; one point (shown below), and SBCL cross-compiled it without
106 ;;; warning about FORMS being undefined. Check whether that problem
107 ;;; (missing warning) is repeatable in the final system and if so, fix
108 ;;; it.
109 #|
110 (defun infinite-error-protector ()
111   `(cond ((not *cold-init-complete-p*)
112           (%primitive print "Argh! error in cold init, halting")
113           (%primitive sb!c:halt))
114          ((or (not (boundp '*current-error-depth*))
115               (not (realp   *current-error-depth*))
116               (not (boundp '*maximum-error-depth*))
117               (not (realp   *maximum-error-depth*)))
118           (%primitive print "Argh! corrupted error depth, halting")
119           (%primitive sb!c:halt))
120          ((> *current-error-depth* *maximum-error-depth*)
121           (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
122           (error-error "Help! "
123                        *current-error-depth*
124                        " nested errors. "
125                        "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
126           (progn ,@forms)
127           t)
128          (t
129           (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
130           nil)))
131 |#
132 \f
133 ;;;; miscellaneous external functions
134
135 #!-mp ; The multi-processing version is defined in multi-proc.lisp.
136 (defun sleep (n)
137   #!+sb-doc
138   "This function causes execution to be suspended for N seconds. N may
139   be any non-negative, non-complex number."
140   (when (or (not (realp n))
141             (minusp n))
142     (error "Invalid argument to SLEEP: ~S.~%~
143             Must be a non-negative, non-complex number."
144            n))
145   (multiple-value-bind (sec usec)
146       (if (integerp n)
147           (values n 0)
148           (multiple-value-bind (sec frac)
149               (truncate n)
150             (values sec(truncate frac 1e-6))))
151     (sb!unix:unix-select 0 0 0 0 sec usec))
152   nil)
153 \f
154 ;;;; SCRUB-CONTROL-STACK
155
156 (defconstant bytes-per-scrub-unit 2048)
157
158 (defun scrub-control-stack ()
159   #!+sb-doc
160   "Zero the unused portion of the control stack so that old objects are not
161    kept alive because of uninitialized stack variables."
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   (declare (optimize (speed 3) (safety 0))
169            (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
170
171   #!-x86 ; machines where stack grows upwards (I guess) -- WHN 19990906
172   (labels
173       ((scrub (ptr offset count)
174          (declare (type system-area-pointer ptr)
175                   (type (unsigned-byte 16) offset)
176                   (type (unsigned-byte 20) count)
177                   (values (unsigned-byte 20)))
178          (cond ((= offset bytes-per-scrub-unit)
179                 (look (sap+ ptr bytes-per-scrub-unit) 0 count))
180                (t
181                 (setf (sap-ref-32 ptr offset) 0)
182                 (scrub ptr (+ offset sb!vm:word-bytes) count))))
183        (look (ptr offset count)
184          (declare (type system-area-pointer ptr)
185                   (type (unsigned-byte 16) offset)
186                   (type (unsigned-byte 20) count)
187                   (values (unsigned-byte 20)))
188          (cond ((= offset bytes-per-scrub-unit)
189                 count)
190                ((zerop (sap-ref-32 ptr offset))
191                 (look ptr (+ offset sb!vm:word-bytes) count))
192                (t
193                 (scrub ptr offset (+ count sb!vm:word-bytes))))))
194     (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
195            (initial-offset (logand csp (1- bytes-per-scrub-unit))))
196       (declare (type (unsigned-byte 32) csp))
197       (scrub (int-sap (- csp initial-offset))
198              (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
199              0)))
200
201   #!+x86 ;; (Stack grows downwards.)
202   (labels
203       ((scrub (ptr offset count)
204          (declare (type system-area-pointer ptr)
205                   (type (unsigned-byte 16) offset)
206                   (type (unsigned-byte 20) count)
207                   (values (unsigned-byte 20)))
208          (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:word-bytes)))))
209            (cond ((= offset bytes-per-scrub-unit)
210                   (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
211                         0 count))
212                  (t ;; need to fix bug in %SET-STACK-REF
213                   (setf (sap-ref-32 loc 0) 0)
214                   (scrub ptr (+ offset sb!vm:word-bytes) count)))))
215        (look (ptr offset count)
216          (declare (type system-area-pointer ptr)
217                   (type (unsigned-byte 16) offset)
218                   (type (unsigned-byte 20) count)
219                   (values (unsigned-byte 20)))
220          (let ((loc (int-sap (- (sap-int ptr) offset))))
221            (cond ((= offset bytes-per-scrub-unit)
222                   count)
223                  ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
224                   (look ptr (+ offset sb!vm:word-bytes) count))
225                  (t
226                   (scrub ptr offset (+ count sb!vm:word-bytes)))))))
227     (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
228            (initial-offset (logand csp (1- bytes-per-scrub-unit))))
229       (declare (type (unsigned-byte 32) csp))
230       (scrub (int-sap (+ csp initial-offset))
231              (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
232              0))))
233 \f
234 ;;;; the default toplevel function
235
236 (defvar / nil
237   #!+sb-doc
238   "a list of all the values returned by the most recent top-level EVAL")
239 (defvar //  nil #!+sb-doc "the previous value of /")
240 (defvar /// nil #!+sb-doc "the previous value of //")
241 (defvar *   nil #!+sb-doc "the value of the most recent top-level EVAL")
242 (defvar **  nil #!+sb-doc "the previous value of *")
243 (defvar *** nil #!+sb-doc "the previous value of **")
244 (defvar +   nil #!+sb-doc "the value of the most recent top-level READ")
245 (defvar ++  nil #!+sb-doc "the previous value of +")
246 (defvar +++ nil #!+sb-doc "the previous value of ++")
247 (defvar -   nil #!+sb-doc "the form currently being evaluated")
248 (defvar *prompt* "* "
249   #!+sb-doc
250   "The top-level prompt string. This also may be a function of no arguments
251    that returns a simple-string.")
252
253 (defun interactive-eval (form)
254   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
255    +++, ++, +, ///, //, /, and -."
256   (setf - form)
257   (let ((results (multiple-value-list (eval form))))
258     (setf /// //
259           // /
260           / results
261           *** **
262           ** *
263           * (car results)))
264   (setf +++ ++
265         ++ +
266         + -)
267   (unless (boundp '*)
268     ;; The bogon returned an unbound marker.
269     ;; FIXME: It would be safer to check every one of the values in RESULTS,
270     ;; instead of just the first one.
271     (setf * nil)
272     (cerror "Go on with * set to NIL."
273             "EVAL returned an unbound marker."))
274   (values-list /))
275
276 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
277 ;;; output streams before proceeding.
278 (defun flush-standard-output-streams ()
279   (dolist (name '(*debug-io*
280                   *error-output*
281                   *query-io*
282                   *standard-output*
283                   *trace-output*))
284     (finish-output (symbol-value name)))
285   (values))
286
287 ;;; the default system top-level function
288 (defun toplevel-init ()
289
290   (/show0 "entering TOPLEVEL-INIT")
291   
292   (let ((sysinit nil)      ; value of --sysinit option
293         (userinit nil)     ; value of --userinit option
294         (evals nil)        ; values of --eval options (in reverse order)
295         (noprint nil)      ; Has a --noprint option been seen?
296         (noprogrammer nil) ; Has a --noprogammer option been seen?
297         (options (rest *posix-argv*))) ; skipping program name
298
299     (/show0 "done with outer LET in TOPLEVEL-INIT")
300   
301     ;; FIXME: There are lots of ways for errors to happen around here (e.g. bad
302     ;; command line syntax, or READ-ERROR while trying to READ an --eval
303     ;; string). Make sure that they're handled reasonably.
304
305     ;; Parse command line options.
306     (loop while options do
307           (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
308           (let ((option (first options)))
309             (flet ((pop-option ()
310                      (if options
311                          (pop options)
312                          (error "unexpected end of command line options"))))
313               (cond ((string= option "--sysinit")
314                      (pop-option)
315                      (if sysinit
316                          (error "multiple --sysinit options")
317                          (setf sysinit (pop-option))))
318                     ((string= option "--userinit")
319                      (pop-option)
320                      (if userinit
321                          (error "multiple --userinit options")
322                          (setf userinit (pop-option))))
323                     ((string= option "--eval")
324                      (pop-option)
325                      (let ((eval-as-string (pop-option)))
326                        (with-input-from-string (eval-stream eval-as-string)
327                          (let* ((eof-marker (cons :eof :eof))
328                                 (eval (read eval-stream nil eof-marker))
329                                 (eof (read eval-stream nil eof-marker)))
330                            (cond ((eq eval eof-marker)
331                                   (error "unable to parse ~S"
332                                          eval-as-string))
333                                  ((not (eq eof eof-marker))
334                                   (error "more than one expression in ~S"
335                                          eval-as-string))
336                                  (t
337                                   (push eval evals)))))))
338                     ((string= option "--noprint")
339                      (pop-option)
340                      (setf noprint t))
341                     ((string= option "--noprogrammer")
342                      (pop-option)
343                      (setf noprogrammer t))
344                     ((string= option "--end-toplevel-options")
345                      (pop-option)
346                      (return))
347                     (t
348                      ;; Anything we don't recognize as a toplevel
349                      ;; option must be the start of user-level
350                      ;; options.. except that if we encounter
351                      ;; "--end-toplevel-options" after we gave up
352                      ;; because we didn't recognize an option as a
353                      ;; toplevel option, then the option we gave up on
354                      ;; must have been an error. (E.g. in
355                      ;;   sbcl --eval '(a)' --evl '(b)' --end-toplevel-options
356                      ;; this test will let us detect that "--evl" is
357                      ;; an error.)
358                      (if (find "--end-toplevel-options" options
359                                :test #'string=)
360                          (error "bad toplevel option: ~S" (first options))
361                          (return)))))))
362     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
363
364     ;; Excise all the options that we processed, so that only user-level
365     ;; options are left visible to user code.
366     (setf (rest *posix-argv*) options)
367
368     ;; FIXME: Verify that errors in init files and/or --eval operations
369     ;; lead to reasonable behavior.
370
371     ;; Handle initialization files.
372     (/show0 "handling initialization files in TOPLEVEL-INIT")
373     (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
374            ;; return its truename.
375            (probe-init-files (&rest possible-init-file-names)
376              (/show0 "entering PROBE-INIT-FILES")
377              (prog1
378                  (find-if (lambda (x)
379                             (and (stringp x) (probe-file x)))
380                           possible-init-file-names)
381                (/show0 "leaving PROBE-INIT-FILES"))))
382       (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
383              (sysinit-truename (if sbcl-home
384                                    (probe-init-files sysinit
385                                                      (concatenate
386                                                       'string
387                                                       sbcl-home
388                                                       "/sbclrc"))
389                                    (probe-init-files sysinit
390                                                      "/etc/sbclrc"
391                                                      "/usr/local/etc/sbclrc")))
392              (user-home (or (posix-getenv "HOME")
393                             (error "The HOME environment variable is unbound, ~
394                                     so user init file can't be found.")))
395              (userinit-truename (probe-init-files userinit
396                                                   (concatenate
397                                                    'string
398                                                    user-home
399                                                    "/.sbclrc"))))
400         (/show0 "assigned SYSINIT-TRUENAME and USERINIT-TRUENAME")
401         (when sysinit-truename
402           (unless (load sysinit-truename)
403             (error "~S was not successfully loaded." sysinit-truename))
404           (flush-standard-output-streams))
405         (/show0 "loaded SYSINIT-TRUENAME")
406         (when userinit-truename
407           (unless (load userinit-truename)
408             (error "~S was not successfully loaded." userinit-truename))
409           (flush-standard-output-streams))
410         (/show0 "loaded USERINIT-TRUENAME"))
411
412       ;; Handle --eval options.
413       (/show0 "handling --eval options in TOPLEVEL-INIT")
414       (dolist (eval (reverse evals))
415         (/show0 "handling one --eval option in TOPLEVEL-INIT")
416         (eval eval)
417         (flush-standard-output-streams))
418
419       ;; Handle stream binding controlled by --noprogrammer option.
420       ;;
421       ;; FIXME: When we do actually implement this, shouldn't it go
422       ;; earlier in the sequence, so that its stream bindings will
423       ;; affect the behavior of init files and --eval options?
424       (/show0 "handling --noprogrammer option in TOPLEVEL-INIT")
425       (when noprogrammer
426         (warn "stub: --noprogrammer option unimplemented")) ; FIXME
427
428       (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
429       (toplevel-repl noprint))))
430
431 ;;; read-eval-print loop for the default system toplevel
432 (defun toplevel-repl (noprint)
433   (/show0 "entering TOPLEVEL-REPL")
434   (let ((* nil) (** nil) (*** nil)
435         (- nil)
436         (+ nil) (++ nil) (+++ nil)
437         (/// nil) (// nil) (/ nil)
438         (eof-marker (cons :eof nil)))
439     (loop
440       (/show0 "at head of outer LOOP in TOPLEVEL-REPL")
441       ;; There should only be one TOPLEVEL restart, and it's here, so
442       ;; restarting at TOPLEVEL always bounces you all the way out here.
443       (with-simple-restart (toplevel
444                             "Restart at toplevel READ/EVAL/PRINT loop.")
445         ;; We add a new ABORT restart for every debugger level, so 
446         ;; restarting at ABORT in a nested debugger gets you out to the
447         ;; innermost enclosing debugger, and only when you're in the
448         ;; outermost, unnested debugger level does restarting at ABORT 
449         ;; get you out to here.
450         (with-simple-restart (abort
451                               "Reduce debugger level (leaving debugger).")
452           (catch 'top-level-catcher
453           (sb!unix:unix-sigsetmask 0)   ; FIXME: What is this for?
454           (/show0 "about to enter inner LOOP in TOPLEVEL-REPL")
455           (loop                         ; FIXME: Do we need this inner LOOP?
456            ;; FIXME: It seems bad to have GC behavior depend on scrubbing
457            ;; the control stack before each interactive command. Isn't
458            ;; there some way we can convince the GC to just ignore
459            ;; dead areas of the control stack, so that we don't need to
460            ;; rely on this half-measure?
461            (scrub-control-stack)
462            (unless noprint
463              (fresh-line)
464              (princ (if (functionp *prompt*)
465                         (funcall *prompt*)
466                         *prompt*))
467              (flush-standard-output-streams))
468            (let ((form (read *standard-input* nil eof-marker)))
469              (if (eq form eof-marker)
470                  (quit)
471                  (let ((results
472                         (multiple-value-list (interactive-eval form))))
473                    (unless noprint
474                      (dolist (result results)
475                        (fresh-line)
476                        (prin1 result)))))))))))))
477 \f
478 ;;; a convenient way to get into the assembly-level debugger
479 (defun %halt ()
480   (%primitive sb!c:halt))