1.0.24.21: call stub needed to switch between hpux heap-spaces
[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 ;;;; magic specials initialized by GENESIS
17
18 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
19 ;;; of all static symbols in early-impl.lisp.
20 (progn
21   (defvar sb!vm::*current-catch-block*)
22   (defvar sb!vm::*current-unwind-protect-block*)
23   #!+hpux (defvar sb!vm::*c-lra*)
24   (defvar *free-interrupt-context-index*))
25 \f
26 ;;; specials initialized by !COLD-INIT
27
28 ;;; FIXME: These could be converted to DEFVARs.
29 (declaim (special #!+(or x86 x86-64) *pseudo-atomic-bits*
30                   *allow-with-interrupts*
31                   *interrupts-enabled*
32                   *interrupt-pending*
33                   *type-system-initialized*))
34
35 (defvar *cold-init-complete-p*)
36
37 ;;; counts of nested errors (with internal errors double-counted)
38 (defvar *maximum-error-depth*)
39 (defvar *current-error-depth*)
40
41 ;;;; default initfiles
42
43 (defun sysinit-pathname ()
44   (or (let ((sbcl-homedir (sbcl-homedir-pathname)))
45         (when sbcl-homedir
46           (probe-file (merge-pathnames "sbclrc" sbcl-homedir))))
47       #!+win32
48       (merge-pathnames "sbcl\\sbclrc"
49                        (sb!win32::get-folder-pathname
50                         sb!win32::csidl_common_appdata))
51       #!-win32
52       "/etc/sbclrc"))
53
54 (defun userinit-pathname ()
55   (merge-pathnames ".sbclrc" (user-homedir-pathname)))
56
57 (defvar *sysinit-pathname-function* #'sysinit-pathname
58   #!+sb-doc
59   "Designator for a function of zero arguments called to obtain a pathname
60 designator for the default sysinit file, or NIL. If the function returns NIL,
61 no sysinit file is used unless one has been specified on the command-line.")
62
63 (defvar *userinit-pathname-function* #'userinit-pathname
64   #!+sb-doc
65   "Designator for a function of zero arguments called to obtain a pathname
66 designator or a stream for the default userinit file, or NIL. If the function
67 returns NIL, no userinit file is used unless one has been specified on the
68 command-line.")
69
70 \f
71 ;;;; miscellaneous utilities for working with with TOPLEVEL
72
73 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
74 ;;; by QUIT) is caught and any final processing and return codes are
75 ;;; handled appropriately.
76 (defmacro handling-end-of-the-world (&body body)
77   (with-unique-names (caught)
78     `(let ((,caught (catch '%end-of-the-world
79                       (/show0 "inside CATCH '%END-OF-THE-WORLD")
80                       (unwind-protect
81                            (progn ,@body)
82                         (call-hooks "exit" *exit-hooks*)))))
83       (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
84       (flush-standard-output-streams)
85       (sb!thread::terminate-session)
86       (/show0 "calling UNIX-EXIT")
87       (sb!unix:unix-exit ,caught))))
88 \f
89 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
90
91 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
92 ;;; of hyperspace.
93 (defmacro infinite-error-protect (&rest forms)
94   `(unless (infinite-error-protector)
95      (/show0 "back from INFINITE-ERROR-PROTECTOR")
96      (let ((*current-error-depth* (1+ *current-error-depth*)))
97        (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
98        ;; arbitrary truncation
99        #!+sb-show (sb!debug:backtrace 8)
100        ,@forms)))
101
102 ;;; a helper function for INFINITE-ERROR-PROTECT
103 (defun infinite-error-protector ()
104   (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
105   (/hexstr *current-error-depth*)
106   (cond ((not *cold-init-complete-p*)
107          (%primitive print "Argh! error in cold init, halting")
108          (%primitive sb!c:halt))
109         ((or (not (boundp '*current-error-depth*))
110              (not (realp   *current-error-depth*))
111              (not (boundp '*maximum-error-depth*))
112              (not (realp   *maximum-error-depth*)))
113          (%primitive print "Argh! corrupted error depth, halting")
114          (%primitive sb!c:halt))
115         ((> *current-error-depth* *maximum-error-depth*)
116          (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
117          (/hexstr *maximum-error-depth*)
118          (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
119          (error-error "Help! "
120                       *current-error-depth*
121                       " nested errors. "
122                       "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
123          t)
124         (t
125          (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
126          nil)))
127
128 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
129 ;;; one point (shown below), and SBCL cross-compiled it without
130 ;;; warning about FORMS being undefined. Check whether that problem
131 ;;; (missing warning) is repeatable in the final system and if so, fix
132 ;;; it.
133 #|
134 (defun infinite-error-protector ()
135   `(cond ((not *cold-init-complete-p*)
136           (%primitive print "Argh! error in cold init, halting")
137           (%primitive sb!c:halt))
138          ((or (not (boundp '*current-error-depth*))
139               (not (realp   *current-error-depth*))
140               (not (boundp '*maximum-error-depth*))
141               (not (realp   *maximum-error-depth*)))
142           (%primitive print "Argh! corrupted error depth, halting")
143           (%primitive sb!c:halt))
144          ((> *current-error-depth* *maximum-error-depth*)
145           (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
146           (error-error "Help! "
147                        *current-error-depth*
148                        " nested errors. "
149                        "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
150           (progn ,@forms)
151           t)
152          (t
153           (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
154           nil)))
155 |#
156 \f
157 ;;;; miscellaneous external functions
158
159 (defun sleep (n)
160   #!+sb-doc
161   "This function causes execution to be suspended for N seconds. N may
162   be any non-negative, non-complex number."
163   (when (or (not (realp n))
164             (minusp n))
165     (error 'simple-type-error
166            :format-control "invalid argument to SLEEP: ~S"
167            :format-arguments (list n)
168            :datum n
169            :expected-type '(real 0)))
170   #!-win32
171   (multiple-value-bind (sec nsec)
172       (if (integerp n)
173           (values n 0)
174           (multiple-value-bind (sec frac)
175               (truncate n)
176             (values sec (truncate frac 1e-9))))
177     (sb!unix:nanosleep sec nsec))
178   #!+win32
179   (sb!win32:millisleep (truncate (* n 1000)))
180   nil)
181 \f
182 ;;;; SCRUB-CONTROL-STACK
183
184 (defconstant bytes-per-scrub-unit 2048)
185
186 ;;; Zero the unused portion of the control stack so that old objects
187 ;;; are not kept alive because of uninitialized stack variables.
188
189 ;;; "To summarize the problem, since not all allocated stack frame
190 ;;; slots are guaranteed to be written by the time you call an another
191 ;;; function or GC, there may be garbage pointers retained in your
192 ;;; dead stack locations.  The stack scrubbing only affects the part
193 ;;; of the stack from the SP to the end of the allocated stack."
194 ;;; - ram, on cmucl-imp, Tue, 25 Sep 2001
195
196 ;;; So, as an (admittedly lame) workaround, from time to time we call
197 ;;; scrub-control-stack to zero out all the unused portion.  This is
198 ;;; supposed to happen when the stack is mostly empty, so that we have
199 ;;; a chance of clearing more of it: callers are currently (2002.07.18)
200 ;;; REPL and SUB-GC
201
202 (defun scrub-control-stack ()
203   (declare (optimize (speed 3) (safety 0))
204            (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
205
206   #!-stack-grows-downward-not-upward
207   (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
208          (initial-offset (logand csp (1- bytes-per-scrub-unit)))
209          (end-of-stack
210           (- (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-end*))
211              sb!c:*backend-page-bytes*)))
212     (labels
213         ((scrub (ptr offset count)
214            (declare (type system-area-pointer ptr)
215                     (type (unsigned-byte 16) offset)
216                     (type (unsigned-byte 20) count)
217                     (values (unsigned-byte 20)))
218            (cond ((>= (sap-int ptr) end-of-stack) 0)
219                  ((= offset bytes-per-scrub-unit)
220                   (look (sap+ ptr bytes-per-scrub-unit) 0 count))
221                  (t
222                   (setf (sap-ref-word ptr offset) 0)
223                   (scrub ptr (+ offset sb!vm:n-word-bytes) count))))
224          (look (ptr offset count)
225            (declare (type system-area-pointer ptr)
226                     (type (unsigned-byte 16) offset)
227                     (type (unsigned-byte 20) count)
228                     (values (unsigned-byte 20)))
229            (cond ((>= (sap-int ptr) end-of-stack) 0)
230                  ((= offset bytes-per-scrub-unit)
231                   count)
232                  ((zerop (sap-ref-word ptr offset))
233                   (look ptr (+ offset sb!vm:n-word-bytes) count))
234                  (t
235                   (scrub ptr offset (+ count sb!vm:n-word-bytes))))))
236       (declare (type sb!vm::word csp))
237       (scrub (int-sap (- csp initial-offset))
238              (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
239              0)))
240
241   #!+stack-grows-downward-not-upward
242   (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
243          (end-of-stack (+ (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-start*))
244                           sb!c:*backend-page-bytes*))
245          (initial-offset (logand csp (1- bytes-per-scrub-unit))))
246     (labels
247         ((scrub (ptr offset count)
248            (declare (type system-area-pointer ptr)
249                     (type (unsigned-byte 16) offset)
250                     (type (unsigned-byte 20) count)
251                     (values (unsigned-byte 20)))
252            (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:n-word-bytes)))))
253              (cond ((< (sap-int loc) end-of-stack) 0)
254                    ((= offset bytes-per-scrub-unit)
255                     (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
256                           0 count))
257                    (t ;; need to fix bug in %SET-STACK-REF
258                     (setf (sap-ref-word loc 0) 0)
259                     (scrub ptr (+ offset sb!vm:n-word-bytes) count)))))
260          (look (ptr offset count)
261            (declare (type system-area-pointer ptr)
262                     (type (unsigned-byte 16) offset)
263                     (type (unsigned-byte 20) count)
264                     (values (unsigned-byte 20)))
265            (let ((loc (int-sap (- (sap-int ptr) offset))))
266              (cond ((< (sap-int loc) end-of-stack) 0)
267                    ((= offset bytes-per-scrub-unit)
268                     count)
269                    ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
270                     (look ptr (+ offset sb!vm:n-word-bytes) count))
271                    (t
272                     (scrub ptr offset (+ count sb!vm:n-word-bytes)))))))
273       (declare (type sb!vm::word csp))
274       (scrub (int-sap (+ csp initial-offset))
275              (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
276              0))))
277 \f
278 ;;;; the default toplevel function
279
280 (defvar / nil
281   #!+sb-doc
282   "a list of all the values returned by the most recent top level EVAL")
283 (defvar //  nil #!+sb-doc "the previous value of /")
284 (defvar /// nil #!+sb-doc "the previous value of //")
285 (defvar *   nil #!+sb-doc "the value of the most recent top level EVAL")
286 (defvar **  nil #!+sb-doc "the previous value of *")
287 (defvar *** nil #!+sb-doc "the previous value of **")
288 (defvar +   nil #!+sb-doc "the value of the most recent top level READ")
289 (defvar ++  nil #!+sb-doc "the previous value of +")
290 (defvar +++ nil #!+sb-doc "the previous value of ++")
291 (defvar -   nil #!+sb-doc "the form currently being evaluated")
292
293 (defun interactive-eval (form)
294   #!+sb-doc
295   "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
296 +++, ++, +, ///, //, /, and -."
297   (setf - form)
298   (unwind-protect
299        (let ((results (multiple-value-list (eval form))))
300          (setf /// //
301                // /
302                / results
303                *** **
304                ** *
305                * (car results)))
306     (setf +++ ++
307           ++ +
308           + -))
309   (unless (boundp '*)
310     ;; The bogon returned an unbound marker.
311     ;; FIXME: It would be safer to check every one of the values in RESULTS,
312     ;; instead of just the first one.
313     (setf * nil)
314     (cerror "Go on with * set to NIL."
315             "EVAL returned an unbound marker."))
316   (values-list /))
317
318 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
319 ;;; output streams before proceeding.
320 (defun flush-standard-output-streams ()
321   (dolist (name '(*debug-io*
322                   *error-output*
323                   *query-io*
324                   *standard-output*
325                   *trace-output*
326                   *terminal-io*))
327     ;; FINISH-OUTPUT may block more easily than FORCE-OUTPUT
328     (force-output (symbol-value name)))
329   (values))
330
331 (defun process-init-file (specified-pathname kind)
332   (multiple-value-bind (context default-function)
333       (ecase kind
334         (:system
335          (values "sysinit" *sysinit-pathname-function*))
336         (:user
337          (values "userinit" *userinit-pathname-function*)))
338     (flet ((process-stream (stream pathname)
339              (with-simple-restart (abort "Skip rest of ~A file ~S."
340                                          context (native-namestring pathname))
341                (loop
342                  (with-simple-restart
343                      (continue "Ignore error and continue processing ~A file ~S."
344                                context (native-namestring pathname))
345                    (let ((form (read stream nil stream)))
346                      (if (eq stream form)
347                          (return-from process-init-file nil)
348                          (eval form))))))))
349       (if specified-pathname
350           (with-open-file (stream (parse-native-namestring specified-pathname)
351                                   :if-does-not-exist nil)
352             (if stream
353                 (process-stream stream (pathname stream))
354                 (cerror "Ignore missing init file"
355                         "The specified ~A file ~A was not found."
356                         context specified-pathname)))
357           (let ((default (funcall default-function)))
358             (when default
359               (with-open-file (stream (pathname default) :if-does-not-exist nil)
360                 (when stream
361                   (process-stream stream (pathname stream))))))))))
362
363 (defun process-eval/load-options (options)
364   (/show0 "handling --eval and --load options")
365   (flet ((process-1 (cons)
366            (destructuring-bind (opt . value) cons
367              (ecase opt
368                (:eval
369                 (with-simple-restart (continue "Ignore runtime option --eval ~S."
370                                                value)
371                   (multiple-value-bind (expr pos) (read-from-string value)
372                     (if (eq value (read-from-string value nil value :start pos))
373                         (eval expr)
374                         (error "Multiple expressions in --eval option: ~S"
375                                value)))))
376                (:load
377                 (with-simple-restart (continue "Ignore runtime option --load ~S."
378                                                value)
379                   (load (native-pathname value))))))
380            (flush-standard-output-streams)))
381     (with-simple-restart (abort "Skip rest of --eval and --load options.")
382       (dolist (option options)
383         (process-1 option)))))
384
385 ;;; Skips past the shebang line on stream, if any.
386 (defun maybe-skip-shebang-line (stream)
387   (let ((p (file-position stream)))
388     (flet ((next () (read-byte stream nil)))
389       (unwind-protect
390            (when (and (eq (next) (char-code #\#))
391                       (eq (next) (char-code #\!)))
392              (setf p nil)
393              (loop for x = (next)
394                    until (or (not x) (eq x (char-code #\newline)))))
395         (when p
396           (file-position stream p))))
397     t))
398
399 (defun process-script (script)
400   (let ((pathname (native-pathname script))
401         (ok nil))
402     (unwind-protect
403          (with-open-file (f pathname :element-type :default)
404            (maybe-skip-shebang-line f)
405            (load f :verbose nil :print nil)
406            (setf ok t))
407       (quit :unix-status (if ok 0 1)))))
408
409 ;; Errors while processing the command line cause the system to QUIT,
410 ;; instead of trying to go into the Lisp debugger, because trying to
411 ;; go into the Lisp debugger would get into various annoying issues of
412 ;; where we should go after the user tries to return from the
413 ;; debugger.
414 (defun startup-error (control-string &rest args)
415   (format *error-output*
416           "fatal error before reaching READ-EVAL-PRINT loop: ~%  ~?~%"
417           control-string
418           args)
419   (quit :unix-status 1))
420
421 ;;; the default system top level function
422 (defun toplevel-init ()
423   (/show0 "entering TOPLEVEL-INIT")
424   (let ( ;; value of --sysinit option
425         (sysinit nil)
426         ;; t if --no-sysinit option given
427         (no-sysinit nil)
428         ;; value of --userinit option
429         (userinit nil)
430         ;; t if --no-userinit option given
431         (no-userinit nil)
432         ;; t if --disable-debugger option given
433         (disable-debugger nil)
434         ;; list of (<kind> . <string>) conses representing --eval and --load
435         ;; options. options. --eval options are stored as strings, so that
436         ;; they can be passed to READ only after their predecessors have been
437         ;; EVALed, so that things work when e.g. REQUIRE in one EVAL form
438         ;; creates a package referred to in the next EVAL form. Storing the
439         ;; original string also makes for easier debugging.
440         (reversed-options nil)
441         ;; Has a --noprint option been seen?
442         (noprint nil)
443         ;; Has a --script option been seen?
444         (script nil)
445         ;; everything in *POSIX-ARGV* except for argv[0]=programname
446         (options (rest *posix-argv*)))
447
448     (declare (type list options))
449
450     (/show0 "done with outer LET in TOPLEVEL-INIT")
451
452     ;; FIXME: There are lots of ways for errors to happen around here
453     ;; (e.g. bad command line syntax, or READ-ERROR while trying to
454     ;; READ an --eval string). Make sure that they're handled
455     ;; reasonably.
456
457     ;; Process command line options.
458     (loop while options do
459          (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
460          (let ((option (first options)))
461            (flet ((pop-option ()
462                     (if options
463                         (pop options)
464                         (startup-error
465                          "unexpected end of command line options"))))
466              (cond ((string= option "--script")
467                     (pop-option)
468                     (setf disable-debugger t
469                           no-userinit t
470                           no-sysinit t
471                           script (pop-option))
472                     (return))
473                    ((string= option "--sysinit")
474                     (pop-option)
475                     (if sysinit
476                         (startup-error "multiple --sysinit options")
477                         (setf sysinit (pop-option))))
478                    ((string= option "--no-sysinit")
479                     (pop-option)
480                     (setf no-sysinit t))
481                    ((string= option "--userinit")
482                     (pop-option)
483                     (if userinit
484                         (startup-error "multiple --userinit options")
485                         (setf userinit (pop-option))))
486                    ((string= option "--no-userinit")
487                     (pop-option)
488                     (setf no-userinit t))
489                    ((string= option "--eval")
490                     (pop-option)
491                     (push (cons :eval (pop-option)) reversed-options))
492                    ((string= option "--load")
493                     (pop-option)
494                     (push (cons :load (pop-option)) reversed-options))
495                    ((string= option "--noprint")
496                     (pop-option)
497                     (setf noprint t))
498                    ((string= option "--disable-debugger")
499                     (pop-option)
500                     (setf disable-debugger t))
501                    ((string= option "--end-toplevel-options")
502                     (pop-option)
503                     (return))
504                    (t
505                     ;; Anything we don't recognize as a toplevel
506                     ;; option must be the start of user-level
507                     ;; options.. except that if we encounter
508                     ;; "--end-toplevel-options" after we gave up
509                     ;; because we didn't recognize an option as a
510                     ;; toplevel option, then the option we gave up on
511                     ;; must have been an error. (E.g. in
512                     ;;  "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
513                     ;; this test will let us detect that the string
514                     ;; "--eval(b)" is an error.)
515                     (if (find "--end-toplevel-options" options
516                               :test #'string=)
517                         (startup-error "bad toplevel option: ~S"
518                                        (first options))
519                         (return)))))))
520     (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
521
522     ;; Delete all the options that we processed, so that only
523     ;; user-level options are left visible to user code.
524     (setf (rest *posix-argv*) options)
525
526     ;; Disable debugger before processing initialization files & co.
527     (when disable-debugger
528       (sb!ext:disable-debugger))
529
530     ;; Handle initialization files.
531     (/show0 "handling initialization files in TOPLEVEL-INIT")
532     ;; This CATCH is needed for the debugger command TOPLEVEL to
533     ;; work.
534     (catch 'toplevel-catcher
535       ;; We wrap all the pre-REPL user/system customized startup
536       ;; code in a restart.
537       ;;
538       ;; (Why not wrap everything, even the stuff above, in this
539       ;; restart? Errors above here are basically command line
540       ;; or Unix environment errors, e.g. a missing file or a
541       ;; typo on the Unix command line, and you don't need to
542       ;; get into Lisp to debug them, you should just start over
543       ;; and do it right at the Unix level. Errors below here
544       ;; are generally errors in user Lisp code, and it might be
545       ;; helpful to let the user reach the REPL in order to help
546       ;; figure out what's going on.)
547       (restart-case
548           (progn
549             (unless no-sysinit
550               (process-init-file sysinit :system))
551             (unless no-userinit
552               (process-init-file userinit :user))
553             (process-eval/load-options (nreverse reversed-options))
554             (when script
555               (process-script script)
556               (bug "PROCESS-SCRIPT returned")))
557         (abort ()
558           :report (lambda (s)
559                     (write-string
560                      (if script
561                          ;; In case script calls (enable-debugger)!
562                          "Abort script, exiting lisp."
563                          "Skip to toplevel READ/EVAL/PRINT loop.")
564                      s))
565           (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
566           (values))                     ; (no-op, just fall through)
567         (quit ()
568           :report "Quit SBCL (calling #'QUIT, killing the process)."
569           :test (lambda (c) (declare (ignore c)) (not script))
570           (/show0 "falling through to QUIT from pre-REPL RESTART-CASE")
571           (quit :unix-status 1))))
572
573     ;; one more time for good measure, in case we fell out of the
574     ;; RESTART-CASE above before one of the flushes in the ordinary
575     ;; flow of control had a chance to operate
576     (flush-standard-output-streams)
577
578     (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
579     (toplevel-repl noprint)
580     ;; (classic CMU CL error message: "You're certainly a clever child.":-)
581     (critically-unreachable "after TOPLEVEL-REPL")))
582
583 ;;; hooks to support customized toplevels like ACL-style toplevel from
584 ;;; KMR on sbcl-devel 2002-12-21.  Altered by CSR 2003-11-16 for
585 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
586 (defvar *repl-read-form-fun* #'repl-read-form-fun
587   #!+sb-doc
588   "A function of two stream arguments IN and OUT for the toplevel REPL to
589 call: Return the next Lisp form to evaluate (possibly handling other magic --
590 like ACL-style keyword commands -- which precede the next Lisp form). The OUT
591 stream is there to support magic which requires issuing new prompts.")
592 (defvar *repl-prompt-fun* #'repl-prompt-fun
593   #!+sb-doc
594   "A function of one argument STREAM for the toplevel REPL to call: Prompt
595 the user for input.")
596 (defvar *repl-fun-generator* (constantly #'repl-fun)
597   #!+sb-doc
598   "A function of no arguments returning a function of one argument NOPRINT
599 that provides the REPL for the system. Assumes that *STANDARD-INPUT* and
600 *STANDARD-OUTPUT* are set up.")
601
602 ;;; read-eval-print loop for the default system toplevel
603 (defun toplevel-repl (noprint)
604   (/show0 "entering TOPLEVEL-REPL")
605   (let ((* nil) (** nil) (*** nil)
606         (- nil)
607         (+ nil) (++ nil) (+++ nil)
608         (/// nil) (// nil) (/ nil))
609     (/show0 "about to funcall *REPL-FUN-GENERATOR*")
610     (let ((repl-fun (funcall *repl-fun-generator*)))
611       ;; Each REPL in a multithreaded world should have bindings of
612       ;; most CL specials (most critically *PACKAGE*).
613       (with-rebound-io-syntax
614           (handler-bind ((step-condition 'invoke-stepper))
615             (loop
616                (/show0 "about to set up restarts in TOPLEVEL-REPL")
617                ;; CLHS recommends that there should always be an
618                ;; ABORT restart; we have this one here, and one per
619                ;; debugger level.
620                (with-simple-restart
621                    (abort "~@<Exit debugger, returning to top level.~@:>")
622                  (catch 'toplevel-catcher
623                    #!-win32 (sb!unix::reset-signal-mask)
624                    ;; In the event of a control-stack-exhausted-error, we
625                    ;; should have unwound enough stack by the time we get
626                    ;; here that this is now possible.
627                    #!-win32
628                    (sb!kernel::protect-control-stack-guard-page 1)
629                    (funcall repl-fun noprint)
630                    (critically-unreachable "after REPL")))))))))
631
632 ;;; Our default REPL prompt is the minimal traditional one.
633 (defun repl-prompt-fun (stream)
634   (fresh-line stream)
635   (write-string "* " stream)) ; arbitrary but customary REPL prompt
636
637 ;;; Our default form reader does relatively little magic, but does
638 ;;; handle the Unix-style EOF-is-end-of-process convention.
639 (defun repl-read-form-fun (in out)
640   (declare (type stream in out) (ignore out))
641   ;; KLUDGE: *READ-SUPPRESS* makes the REPL useless, and cannot be
642   ;; recovered from -- flip it here.
643   (when *read-suppress*
644     (warn "Setting *READ-SUPPRESS* to NIL to restore toplevel usability.")
645     (setf *read-suppress* nil))
646   (let* ((eof-marker (cons nil nil))
647          (form (read in nil eof-marker)))
648     (if (eq form eof-marker)
649         (quit)
650         form)))
651
652 (defun repl-fun (noprint)
653   (/show0 "entering REPL")
654   (loop
655    (unwind-protect
656         (progn
657           ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
658           (scrub-control-stack)
659           (sb!thread::get-foreground)
660           (unless noprint
661             (flush-standard-output-streams)
662             (funcall *repl-prompt-fun* *standard-output*)
663             ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
664             ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
665             ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
666             ;; odd. But maybe there *is* a valid reason in some
667             ;; circumstances? perhaps some deadlock issue when being driven
668             ;; by another process or something...)
669             (force-output *standard-output*))
670           (let* ((form (funcall *repl-read-form-fun*
671                                 *standard-input*
672                                 *standard-output*))
673                  (results (multiple-value-list (interactive-eval form))))
674             (unless noprint
675               (dolist (result results)
676                 (fresh-line)
677                 (prin1 result)))))
678      ;; If we started stepping in the debugger we want to stop now.
679      (disable-stepping))))
680 \f
681 ;;; a convenient way to get into the assembly-level debugger
682 (defun %halt ()
683   (%primitive sb!c:halt))