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