0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[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                       ,@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 (defvar *in-top-level-catcher* nil
253   #!+sb-doc
254   "Are we within the Top-Level-Catcher? This is used by interrupt
255    handlers to see whether it is OK to throw.")
256
257 (defun interactive-eval (form)
258   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
259    +++, ++, +, ///, //, /, and -."
260   (setf - form)
261   (let ((results (multiple-value-list (eval form))))
262     (setf /// //
263           // /
264           / results
265           *** **
266           ** *
267           * (car results)))
268   (setf +++ ++
269         ++ +
270         + -)
271   (unless (boundp '*)
272     ;; The bogon returned an unbound marker.
273     ;; FIXME: It would be safer to check every one of the values in RESULTS,
274     ;; instead of just the first one.
275     (setf * nil)
276     (cerror "Go on with * set to NIL."
277             "EVAL returned an unbound marker."))
278   (values-list /))
279
280 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
281 ;;; output streams before proceeding.
282 (defun flush-standard-output-streams ()
283   (dolist (name '(*debug-io*
284                   *error-output*
285                   *query-io*
286                   *standard-output*
287                   *trace-output*))
288     (finish-output (symbol-value name)))
289   (values))
290
291 ;;; the default system top-level function
292 (defun toplevel ()
293
294   (/show0 "entering TOPLEVEL")
295   
296   (let ((sysinit nil)      ; value of --sysinit option
297         (userinit nil)     ; value of --userinit option
298         (evals nil)        ; values of --eval options (in reverse order)
299         (noprint nil)      ; Has a --noprint option been seen?
300         (noprogrammer nil) ; Has a --noprogammer option been seen?
301         (options (rest *posix-argv*))) ; skipping program name
302
303     (/show0 "done with outer LET in TOPLEVEL")
304   
305     ;; FIXME: There are lots of ways for errors to happen around here (e.g. bad
306     ;; command line syntax, or READ-ERROR while trying to READ an --eval
307     ;; string). Make sure that they're handled reasonably.
308
309     ;; Parse command line options.
310     (loop while options do
311           (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL")
312           (let ((option (first options)))
313             (flet ((pop-option ()
314                      (if options
315                          (pop options)
316                          (error "unexpected end of command line options"))))
317               (cond ((string= option "--sysinit")
318                      (pop-option)
319                      (if sysinit
320                          (error "multiple --sysinit options")
321                          (setf sysinit (pop-option))))
322                     ((string= option "--userinit")
323                      (pop-option)
324                      (if userinit
325                          (error "multiple --userinit options")
326                          (setf userinit (pop-option))))
327                     ((string= option "--eval")
328                      (pop-option)
329                      (let ((eval-as-string (pop-option)))
330                        (with-input-from-string (eval-stream eval-as-string)
331                          (let* ((eof-marker (cons :eof :eof))
332                                 (eval (read eval-stream nil eof-marker))
333                                 (eof (read eval-stream nil eof-marker)))
334                            (cond ((eq eval eof-marker)
335                                   (error "unable to parse ~S"
336                                          eval-as-string))
337                                  ((not (eq eof eof-marker))
338                                   (error "more than one expression in ~S"
339                                          eval-as-string))
340                                  (t
341                                   (push eval evals)))))))
342                     ((string= option "--noprint")
343                      (pop-option)
344                      (setf noprint t))
345                     ((string= option "--noprogrammer")
346                      (pop-option)
347                      (setf noprogrammer t))
348                     ((string= option "--end-toplevel-options")
349                      (pop-option)
350                      (return))
351                     (t
352                      ;; Anything we don't recognize as a toplevel
353                      ;; option must be the start of user-level
354                      ;; options.. except that if we encounter
355                      ;; "--end-toplevel-options" after we gave up
356                      ;; because we didn't recognize an option as a
357                      ;; toplevel option, then the option we gave up on
358                      ;; must have been an error. (E.g. in
359                      ;;   sbcl --eval '(a)' --evl '(b)' --end-toplevel-options
360                      ;; this test will let us detect that "--evl" is
361                      ;; an error.)
362                      (if (find "--end-toplevel-options" options
363                                :test #'string=)
364                          (error "bad toplevel option: ~S" (first options))
365                          (return)))))))
366     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL")
367
368     ;; Excise all the options that we processed, so that only user-level
369     ;; options are left visible to user code.
370     (setf (rest *posix-argv*) options)
371
372     ;; FIXME: Verify that errors in init files and/or --eval operations
373     ;; lead to reasonable behavior.
374
375     ;; Handle initialization files.
376     (/show0 "handling initialization files in TOPLEVEL")
377     (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
378            ;; return its truename.
379            (probe-init-files (&rest possible-init-file-names)
380              (/show0 "entering PROBE-INIT-FILES")
381              (prog1
382                  (find-if (lambda (x)
383                             (and (stringp x) (probe-file x)))
384                           possible-init-file-names)
385                (/show0 "leaving PROBE-INIT-FILES"))))
386       (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
387              #!+sb-show(ignore1 (progn
388                                   (/show0 "SBCL-HOME=..")
389                                   (if sbcl-home
390                                       (%primitive print sbcl-home)
391                                       (%primitive print "NIL"))))
392              (sysinit-truename (if sbcl-home
393                                    (probe-init-files sysinit
394                                                      (concatenate
395                                                       'string
396                                                       sbcl-home
397                                                       "/sbclrc"))
398                                    (probe-init-files sysinit
399                                                      "/etc/sbclrc"
400                                                      "/usr/local/etc/sbclrc")))
401              (user-home (or (posix-getenv "HOME")
402                             (error "The HOME environment variable is unbound, ~
403                                     so user init file can't be found.")))
404              #!+sb-show(ignore2 (progn
405                                   (/show0 "USER-HOME=..")
406                                   (%primitive print user-home)))
407              (userinit-truename (probe-init-files userinit
408                                                   (concatenate
409                                                    'string
410                                                    user-home
411                                                    "/.sbclrc"))))
412         (/show0 "assigned SYSINIT-TRUENAME and USERINIT-TRUENAME")
413         (when sysinit-truename
414           (/show0 "SYSINIT-TRUENAME=..")
415           #!+sb-show (%primitive print 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           (/show0 "USERINIT-TRUENAME=..")
422           #!+sb-show (%primitive print userinit-truename)
423           (unless (load userinit-truename)
424             (error "~S was not successfully loaded." userinit-truename))
425           (flush-standard-output-streams))
426         (/show0 "loaded USERINIT-TRUENAME"))
427
428       ;; Handle --eval options.
429       (/show0 "handling --eval options in TOPLEVEL")
430       (dolist (eval (reverse evals))
431         (/show0 "handling one --eval option in TOPLEVEL")
432         (eval eval)
433         (flush-standard-output-streams))
434
435       ;; Handle stream binding controlled by --noprogrammer option.
436       ;;
437       ;; FIXME: When we do actually implement this, shouldn't it go
438       ;; earlier in the sequence, so that its stream bindings will
439       ;; affect the behavior of init files and --eval options?
440       (/show0 "handling --noprogrammer option in TOPLEVEL")
441       (when noprogrammer
442         (warn "stub: --noprogrammer option unimplemented")) ; FIXME
443
444       (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL")
445       (toplevel-repl noprint))))
446
447 ;;; read-eval-print loop for the default system toplevel
448 (defun toplevel-repl (noprint)
449   (/show0 "entering TOPLEVEL-REPL")
450   (let ((* nil) (** nil) (*** nil)
451         (- nil)
452         (+ nil) (++ nil) (+++ nil)
453         (/// nil) (// nil) (/ nil)
454         (eof-marker (cons :eof nil)))
455     (loop
456       ;; FIXME: This seems to be the source of one of the basic debugger
457       ;; choices in
458       ;;    Restarts:
459       ;;      0: [CONTINUE] Return from BREAK.
460       ;;      1: [ABORT   ] Return to toplevel.
461       ;; (The "Return from BREAK" choice is defined in BREAK.) I'd like to add
462       ;; another choice,
463       ;;      2: [TERMINATE] Terminate the current Lisp.
464       ;; That way, a user hitting ^C could get out of Lisp without knowing
465       ;; enough about the system to run (SB-EXT:QUIT).
466       ;;
467       ;; If I understand the documentation of WITH-SIMPLE-RESTART correctly,
468       ;; it shows how to replace this WITH-SIMPLE-RESTART with a RESTART-CASE
469       ;; with two choices (ABORT and QUIT). Or perhaps ABORT should be renamed
470       ;; TOPLEVEL?
471       ;;    Restarts:
472       ;;      0: [CONTINUE ] Return from BREAK, continuing calculation
473       ;;                     as though nothing happened.
474       ;;      1: [TOPLEVEL ] Transfer control to toplevel read/eval/print
475       ;;                     loop, aborting current calculation.
476       ;;      2: [TERMINATE] Terminate the current Lisp (equivalent to
477       ;;                     executing (SB-EXT:QUIT)).
478       (/show0 "at head of outer LOOP in TOPLEVEL-REPL")
479       (with-simple-restart (abort "Return to toplevel.")
480         (catch 'top-level-catcher
481           (sb!unix:unix-sigsetmask 0) ; FIXME: What is this for?
482           (let ((*in-top-level-catcher* t))
483             (/show0 "about to enter inner LOOP in TOPLEVEL-REPL")
484             (loop                       ; FIXME: Do we need this inner LOOP?
485              ;; FIXME: It seems bad to have GC behavior depend on scrubbing
486              ;; the control stack before each interactive command. Isn't
487              ;; there some way we can convince the GC to just ignore
488              ;; dead areas of the control stack, so that we don't need to
489              ;; rely on this half-measure?
490              (scrub-control-stack)
491              (unless noprint
492                (fresh-line)
493                (princ (if (functionp *prompt*)
494                           (funcall *prompt*)
495                           *prompt*))
496                (flush-standard-output-streams))
497              (let ((form (read *standard-input* nil eof-marker)))
498                (if (eq form eof-marker)
499                    (quit)
500                    (let ((results
501                           (multiple-value-list (interactive-eval form))))
502                      (unless noprint
503                        (dolist (result results)
504                          (fresh-line)
505                          (prin1 result)))))))))))))
506 \f
507 ;;; a convenient way to get into the assembly-level debugger
508 (defun %halt ()
509   (%primitive sb!c:halt))