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