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