0.7.5.22:
[sbcl.git] / src / code / reader.lisp
1 ;;;; READ and friends
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; miscellaneous global variables
15
16 ;;; ANSI: "the floating-point format that is to be used when reading a
17 ;;; floating-point number that has no exponent marker or that has e or
18 ;;; E for an exponent marker"
19 (defvar *read-default-float-format* 'single-float)
20 (declaim (type (member short-float single-float double-float long-float)
21                *read-default-float-format*))
22
23 (defvar *readtable*)
24 (declaim (type readtable *readtable*))
25 #!+sb-doc
26 (setf (fdocumentation '*readtable* 'variable)
27        "Variable bound to current readtable.")
28
29 ;;; a standard Lisp readtable. This is for recovery from broken
30 ;;; read-tables (and for WITH-STANDARD-IO-SYNTAX), and should not
31 ;;; normally be user-visible.
32 (defvar *standard-readtable*)
33
34 (defvar *old-package* nil
35   #!+sb-doc
36   "the value of *PACKAGE* at the start of the last read, or NIL")
37
38 ;;; In case we get an error trying to parse a symbol, we want to rebind the
39 ;;; above stuff so it's cool.
40
41 ;;; FIXME: These forward declarations should be moved somewhere earlier,
42 ;;; or discarded.
43 (declaim (special *package* *keyword-package* *read-base*))
44 \f
45 ;;;; reader errors
46
47 (defun reader-eof-error (stream context)
48   (error 'reader-eof-error
49          :stream stream
50          :context context))
51
52 (defun %reader-error (stream control &rest args)
53   (error 'reader-error
54          :stream stream
55          :format-control control
56          :format-arguments args))
57 \f
58 ;;;; macros and functions for character tables
59
60 ;;; FIXME: could be SB!XC:DEFMACRO inside EVAL-WHEN (COMPILE EVAL)
61 (defmacro get-cat-entry (char rt)
62   ;; KLUDGE: Only give this side-effect-free args.
63   ;; FIXME: should probably become inline function
64   `(elt (character-attribute-table ,rt)
65         (char-code ,char)))
66
67 (defun set-cat-entry (char newvalue &optional (rt *readtable*))
68   (setf (elt (character-attribute-table rt)
69              (char-code char))
70         newvalue))
71
72 ;;; the value actually stored in the character macro table. As per
73 ;;; ANSI #'GET-MACRO-CHARACTER and #'SET-MACRO-CHARACTER, this can
74 ;;; be either a function or NIL.
75 (eval-when (:compile-toplevel :execute)
76   (sb!xc:defmacro get-raw-cmt-entry (char readtable)
77     `(svref (character-macro-table ,readtable)
78             (char-code ,char))))
79
80 ;;; the value represented by whatever is stored in the character macro
81 ;;; table. As per ANSI #'GET-MACRO-CHARACTER and #'SET-MACRO-CHARACTER,
82 ;;; a function value represents itself, and a NIL value represents the
83 ;;; default behavior.
84 (defun get-coerced-cmt-entry (char readtable)
85   (the function 
86     (or (get-raw-cmt-entry char readtable)
87         #'read-token)))
88
89 (defun set-cmt-entry (char new-value-designator &optional (rt *readtable*))
90   (setf (svref (character-macro-table rt)
91                (char-code char))
92         (and new-value-designator
93              (%coerce-callable-to-fun new-value-designator))))
94
95 (defun undefined-macro-char (stream char)
96   (unless *read-suppress*
97     (%reader-error stream "undefined read-macro character ~S" char)))
98
99 ;;; The character attribute table is a CHAR-CODE-LIMIT vector of integers.
100
101 (defmacro test-attribute (char whichclass rt)
102   `(= (the fixnum (get-cat-entry ,char ,rt)) ,whichclass))
103
104 ;;; predicates for testing character attributes
105
106 #!-sb-fluid (declaim (inline whitespacep))
107 (defun whitespacep (char &optional (rt *readtable*))
108   (test-attribute char +char-attr-whitespace+ rt))
109
110 (defmacro constituentp (char &optional (rt '*readtable*))
111   `(>= (get-cat-entry ,char ,rt) +char-attr-constituent+))
112
113 (defmacro terminating-macrop (char &optional (rt '*readtable*))
114   `(test-attribute ,char +char-attr-terminating-macro+ ,rt))
115
116 (defmacro escapep (char &optional (rt '*readtable*))
117   `(test-attribute ,char +char-attr-escape+ ,rt))
118
119 (defmacro multiple-escape-p (char &optional (rt '*readtable*))
120   `(test-attribute ,char +char-attr-multiple-escape+ ,rt))
121
122 (defmacro token-delimiterp (char &optional (rt '*readtable*))
123   ;; depends on actual attribute numbering above.
124   `(<= (get-cat-entry ,char ,rt) +char-attr-terminating-macro+))
125 \f
126 ;;;; secondary attribute table
127
128 ;;; There are a number of "secondary" attributes which are constant
129 ;;; properties of characters (as long as they are constituents).
130
131 (defvar *secondary-attribute-table*)
132 (declaim (type attribute-table *secondary-attribute-table*))
133
134 (defun !set-secondary-attribute (char attribute)
135   (setf (elt *secondary-attribute-table* (char-code char))
136         attribute))
137
138 (defun !cold-init-secondary-attribute-table ()
139   (setq *secondary-attribute-table*
140         (make-array char-code-limit :element-type '(unsigned-byte 8)
141                     :initial-element +char-attr-constituent+))
142   (!set-secondary-attribute #\: +char-attr-package-delimiter+)
143   (!set-secondary-attribute #\| +char-attr-multiple-escape+) ; |) [for EMACS]
144   (!set-secondary-attribute #\. +char-attr-constituent-dot+)
145   (!set-secondary-attribute #\+ +char-attr-constituent-sign+)
146   (!set-secondary-attribute #\- +char-attr-constituent-sign+)
147   (!set-secondary-attribute #\/ +char-attr-constituent-slash+)
148   (do ((i (char-code #\0) (1+ i)))
149       ((> i (char-code #\9)))
150     (!set-secondary-attribute (code-char i) +char-attr-constituent-digit+))
151   (!set-secondary-attribute #\E +char-attr-constituent-expt+)
152   (!set-secondary-attribute #\F +char-attr-constituent-expt+)
153   (!set-secondary-attribute #\D +char-attr-constituent-expt+)
154   (!set-secondary-attribute #\S +char-attr-constituent-expt+)
155   (!set-secondary-attribute #\L +char-attr-constituent-expt+)
156   (!set-secondary-attribute #\e +char-attr-constituent-expt+)
157   (!set-secondary-attribute #\f +char-attr-constituent-expt+)
158   (!set-secondary-attribute #\d +char-attr-constituent-expt+)
159   (!set-secondary-attribute #\s +char-attr-constituent-expt+)
160   (!set-secondary-attribute #\l +char-attr-constituent-expt+))
161
162 (defmacro get-secondary-attribute (char)
163   `(elt *secondary-attribute-table*
164         (char-code ,char)))
165 \f
166 ;;;; readtable operations
167
168 (defun copy-readtable (&optional (from-readtable *readtable*)
169                                  to-readtable)
170   (let ((really-from-readtable (or from-readtable *standard-readtable*))
171         (really-to-readtable (or to-readtable (make-readtable))))
172     (replace (character-attribute-table really-to-readtable)
173              (character-attribute-table really-from-readtable))
174     (replace (character-macro-table really-to-readtable)
175              (character-macro-table really-from-readtable))
176     (setf (dispatch-tables really-to-readtable)
177           (mapcar (lambda (pair) (cons (car pair)
178                                        (copy-seq (cdr pair))))
179                   (dispatch-tables really-from-readtable)))
180     (setf (readtable-case really-to-readtable)
181           (readtable-case really-from-readtable))
182     really-to-readtable))
183
184 (defun set-syntax-from-char (to-char from-char &optional
185                                      (to-readtable *readtable*)
186                                      (from-readtable ()))
187   #!+sb-doc
188   "Causes the syntax of TO-CHAR to be the same as FROM-CHAR in the
189   optional readtable (defaults to the current readtable). The
190   FROM-TABLE defaults to the standard Lisp readtable when NIL."
191   (let ((really-from-readtable (or from-readtable *standard-readtable*)))
192     ;; Copy FROM-CHAR entries to TO-CHAR entries, but make sure that if
193     ;; FROM-CHAR is a constituent you don't copy non-movable secondary
194     ;; attributes (constituent types), and that said attributes magically
195     ;; appear if you transform a non-constituent to a constituent.
196     (let ((att (get-cat-entry from-char really-from-readtable)))
197       (if (constituentp from-char really-from-readtable)
198           (setq att (get-secondary-attribute to-char)))
199       (set-cat-entry to-char att to-readtable)
200       (set-cmt-entry to-char
201                      (get-raw-cmt-entry from-char really-from-readtable)
202                      to-readtable)))
203   t)
204
205 (defun set-macro-character (char function &optional
206                                  (non-terminatingp nil)
207                                  (readtable *readtable*))
208   #!+sb-doc
209   "Causes CHAR to be a macro character which invokes FUNCTION when seen
210    by the reader. The NON-TERMINATINGP flag can be used to make the macro
211    character non-terminating, i.e. embeddable in a symbol name."
212   (let ((designated-readtable (or readtable *standard-readtable*)))
213     (set-cat-entry char
214                    (if non-terminatingp
215                        (get-secondary-attribute char)
216                        +char-attr-terminating-macro+)
217                    designated-readtable)
218     (set-cmt-entry char function designated-readtable)
219     t)) ; (ANSI-specified return value)
220
221 (defun get-macro-character (char &optional (readtable *readtable*))
222   #!+sb-doc
223   "Return the function associated with the specified CHAR which is a macro
224   character, or NIL if there is no such function. As a second value, return
225   T if CHAR is a macro character which is non-terminating, i.e. which can
226   be embedded in a symbol name."
227   (let* ((designated-readtable (or readtable *standard-readtable*))
228          ;; the first return value: a FUNCTION if CHAR is a macro
229          ;; character, or NIL otherwise
230          (fun-value (get-raw-cmt-entry char designated-readtable)))
231     (values fun-value
232             ;; NON-TERMINATING-P return value:
233             (if fun-value
234                 (or (constituentp char)
235                     (not (terminating-macrop char)))
236                 ;; ANSI's definition of GET-MACRO-CHARACTER says this
237                 ;; value is NIL when CHAR is not a macro character.
238                 ;; I.e. this value means not just "non-terminating
239                 ;; character?" but "non-terminating macro character?".
240                 nil))))
241 \f
242 ;;;; definitions to support internal programming conventions
243
244 (defmacro eofp (char)
245   `(eq ,char *eof-object*))
246
247 (defun flush-whitespace (stream)
248   ;; This flushes whitespace chars, returning the last char it read (a
249   ;; non-white one). It always gets an error on end-of-file.
250   (let ((stream (in-synonym-of stream)))
251     (if (ansi-stream-p stream)
252         (prepare-for-fast-read-char stream
253           (do ((attribute-table (character-attribute-table *readtable*))
254                (char (fast-read-char t) (fast-read-char t)))
255               ((/= (the fixnum (aref attribute-table (char-code char)))
256                    +char-attr-whitespace+)
257                (done-with-fast-read-char)
258                char)))
259         ;; fundamental-stream
260         (do ((attribute-table (character-attribute-table *readtable*))
261              (char (stream-read-char stream) (stream-read-char stream)))
262             ((or (eq char :eof)
263                  (/= (the fixnum (aref attribute-table (char-code char)))
264                      +char-attr-whitespace+))
265              (if (eq char :eof)
266                  (error 'end-of-file :stream stream)
267                  char))))))
268 \f
269 ;;;; temporary initialization hack
270
271 (defun !cold-init-standard-readtable ()
272   (setq *standard-readtable* (make-readtable))
273   ;; All characters get boring defaults in MAKE-READTABLE. Now we
274   ;; override the boring defaults on characters which need more
275   ;; interesting behavior.
276   (let ((*readtable* *standard-readtable*))
277
278     (flet ((whitespaceify (char)
279              (set-cat-entry char +char-attr-whitespace+)))
280       (whitespaceify (code-char tab-char-code))
281       (whitespaceify #\linefeed)
282       (whitespaceify #\space)
283       (whitespaceify (code-char form-feed-char-code))
284       (whitespaceify (code-char return-char-code)))
285
286     (set-cat-entry #\\ +char-attr-escape+)
287     (set-cmt-entry #\\ #'read-token)
288
289     ;; Easy macro-character definitions are in this source file.
290     (set-macro-character #\" #'read-string)
291     (set-macro-character #\' #'read-quote)
292     (set-macro-character #\( #'read-list)
293     (set-macro-character #\) #'read-right-paren)
294     (set-macro-character #\; #'read-comment)
295     ;; (The hairier macro-character definitions, for #\# and #\`, are
296     ;; defined elsewhere, in their own source files.)
297
298     ;; all constituents
299     (do ((ichar 0 (1+ ichar))
300          (char))
301         ((= ichar #O200))
302       (setq char (code-char ichar))
303       (when (constituentp char *standard-readtable*)
304             (set-cat-entry char (get-secondary-attribute char))
305             (set-cmt-entry char nil)))))
306 \f
307 ;;;; implementation of the read buffer
308
309 (defvar *read-buffer*)
310 (defvar *read-buffer-length*)
311 ;;; FIXME: Is it really helpful to have *READ-BUFFER-LENGTH* be a
312 ;;; separate variable instead of just calculating it on the fly as
313 ;;; (LENGTH *READ-BUFFER*)?
314
315 (defvar *inch-ptr*)
316 (defvar *ouch-ptr*)
317
318 (declaim (type index *read-buffer-length* *inch-ptr* *ouch-ptr*))
319 (declaim (simple-string *read-buffer*))
320
321 (defmacro reset-read-buffer ()
322   ;; Turn *READ-BUFFER* into an empty read buffer.
323   `(progn
324      ;; *OUCH-PTR* always points to next char to write.
325      (setq *ouch-ptr* 0)
326      ;; *INCH-PTR* always points to next char to read.
327      (setq *inch-ptr* 0)))
328
329 (defun !cold-init-read-buffer ()
330   (setq *read-buffer* (make-string 512)) ; initial bufsize
331   (setq *read-buffer-length* 512)
332   (reset-read-buffer))
333
334 ;;; FIXME I removed "THE FIXNUM"'s from OUCH-READ-BUFFER and
335 ;;; OUCH-UNREAD-BUFFER, check to make sure that Python really is smart
336 ;;; enough to make good code without them. And while I'm at it,
337 ;;; converting them from macros to inline functions might be good,
338 ;;; too.
339
340 (defmacro ouch-read-buffer (char)
341   `(progn
342      ;; When buffer overflow
343      (when (>= *ouch-ptr* *read-buffer-length*)
344        ;; Size should be doubled.
345        (grow-read-buffer))
346      (setf (elt (the simple-string *read-buffer*) *ouch-ptr*) ,char)
347      (setq *ouch-ptr* (1+ *ouch-ptr*))))
348
349 ;;; macro to move *ouch-ptr* back one.
350 (defmacro ouch-unread-buffer ()
351   '(when (> *ouch-ptr* *inch-ptr*)
352      (setq *ouch-ptr* (1- (the fixnum *ouch-ptr*)))))
353
354 (defun grow-read-buffer ()
355   (let ((rbl (length (the simple-string *read-buffer*))))
356     (setq *read-buffer*
357           (concatenate 'simple-string
358                        *read-buffer*
359                        (make-string rbl)))
360     (setq *read-buffer-length* (* 2 rbl))))
361
362 (defun inchpeek-read-buffer ()
363   (if (>= (the fixnum *inch-ptr*) (the fixnum *ouch-ptr*))
364       *eof-object*
365       (elt *read-buffer* *inch-ptr*)))
366
367 (defun inch-read-buffer ()
368   (if (>= *inch-ptr* *ouch-ptr*)
369       *eof-object*
370       (prog1
371           (elt *read-buffer* *inch-ptr*)
372         (incf *inch-ptr*))))
373
374 (defmacro unread-buffer ()
375   `(decf *inch-ptr*))
376
377 (defun read-unwind-read-buffer ()
378   ;; Keep contents, but make next (INCH..) return first character.
379   (setq *inch-ptr* 0))
380
381 (defun read-buffer-to-string ()
382   (subseq *read-buffer* 0 *ouch-ptr*))
383 \f
384 ;;;; READ-PRESERVING-WHITESPACE, READ-DELIMITED-LIST, and READ
385
386 ;;; an alist for #=, used to keep track of objects with labels assigned that
387 ;;; have been completely read. Each entry is (integer-tag gensym-tag value).
388 ;;;
389 ;;; KLUDGE: Should this really be an alist? It seems as though users
390 ;;; could reasonably expect N log N performance for large datasets.
391 ;;; On the other hand, it's probably very very seldom a problem in practice.
392 ;;; On the third hand, it might be just as easy to use a hash table
393 ;;; as an alist, so maybe we should. -- WHN 19991202
394 (defvar *sharp-equal-alist* ())
395
396 (declaim (special *standard-input*))
397
398 ;;; READ-PRESERVING-WHITESPACE behaves just like READ, only it makes
399 ;;; sure to leave terminating whitespace in the stream. (This is a
400 ;;; COMMON-LISP exported symbol.)
401 (defun read-preserving-whitespace (&optional (stream *standard-input*)
402                                              (eof-error-p t)
403                                              (eof-value nil)
404                                              (recursivep nil))
405   #!+sb-doc
406   "Read from STREAM and return the value read, preserving any whitespace
407    that followed the object."
408   (if recursivep
409     ;; a loop for repeating when a macro returns nothing
410     (loop
411       (let ((char (read-char stream eof-error-p *eof-object*)))
412         (cond ((eofp char) (return eof-value))
413               ((whitespacep char))
414               (t
415                (let* ((macrofun (get-coerced-cmt-entry char *readtable*))
416                       (result (multiple-value-list
417                                (funcall macrofun stream char))))
418                  ;; Repeat if macro returned nothing.
419                   (if result (return (car result))))))))
420     (let ((*sharp-equal-alist* nil))
421         (read-preserving-whitespace stream eof-error-p eof-value t))))
422
423 ;;; Return NIL or a list with one thing, depending.
424 ;;;
425 ;;; for functions that want comments to return so that they can look
426 ;;; past them. We assume CHAR is not whitespace.
427 (defun read-maybe-nothing (stream char)
428   (let ((retval (multiple-value-list
429                  (funcall (get-coerced-cmt-entry char *readtable*)
430                           stream
431                           char))))
432     (if retval (rplacd retval nil))))
433
434 (defun read (&optional (stream *standard-input*)
435                        (eof-error-p t)
436                        (eof-value ())
437                        (recursivep ()))
438   #!+sb-doc
439   "Read the next Lisp value from STREAM, and return it."
440   (let ((result (read-preserving-whitespace stream
441                                             eof-error-p
442                                             eof-value
443                                             recursivep)))
444     ;; (This function generally discards trailing whitespace. If you
445     ;; don't want to discard trailing whitespace, call
446     ;; CL:READ-PRESERVING-WHITESPACE instead.)
447     (unless (or (eql result eof-value) recursivep)
448       (let ((next-char (read-char stream nil nil)))
449         (unless (or (null next-char)
450                     (whitespacep next-char))
451           (unread-char next-char stream))))
452     result))
453
454 ;;; (This is a COMMON-LISP exported symbol.)
455 (defun read-delimited-list (endchar &optional
456                                     (input-stream *standard-input*)
457                                     recursive-p)
458   #!+sb-doc
459   "Read Lisp values from INPUT-STREAM until the next character after a
460    value's representation is ENDCHAR, and return the objects as a list."
461   (declare (ignore recursive-p))
462   (do ((char (flush-whitespace input-stream)
463              (flush-whitespace input-stream))
464        (retlist ()))
465       ((char= char endchar) (nreverse retlist))
466     (setq retlist (nconc (read-maybe-nothing input-stream char) retlist))))
467 \f
468 ;;;; basic readmacro definitions
469 ;;;;
470 ;;;; Some large, hairy subsets of readmacro definitions (backquotes
471 ;;;; and sharp macros) are not here, but in their own source files.
472
473 (defun read-quote (stream ignore)
474   (declare (ignore ignore))
475   (list 'quote (read stream t nil t)))
476
477 (defun read-comment (stream ignore)
478   (declare (ignore ignore))
479   (let ((stream (in-synonym-of stream)))
480     (if (ansi-stream-p stream)
481         (prepare-for-fast-read-char stream
482           (do ((char (fast-read-char nil nil)
483                      (fast-read-char nil nil)))
484               ((or (not char) (char= char #\newline))
485                (done-with-fast-read-char))))
486         ;; FUNDAMENTAL-STREAM
487         (do ((char (stream-read-char stream) (stream-read-char stream)))
488             ((or (eq char :eof) (char= char #\newline))))))
489   ;; Don't return anything.
490   (values))
491
492 (defun read-list (stream ignore)
493   (declare (ignore ignore))
494   (let* ((thelist (list nil))
495          (listtail thelist))
496     (do ((firstchar (flush-whitespace stream) (flush-whitespace stream)))
497         ((char= firstchar #\) ) (cdr thelist))
498       (when (char= firstchar #\.)
499             (let ((nextchar (read-char stream t)))
500               (cond ((token-delimiterp nextchar)
501                      (cond ((eq listtail thelist)
502                             (%reader-error
503                              stream
504                              "Nothing appears before . in list."))
505                            ((whitespacep nextchar)
506                             (setq nextchar (flush-whitespace stream))))
507                      (rplacd listtail
508                              ;; Return list containing last thing.
509                              (car (read-after-dot stream nextchar)))
510                      (return (cdr thelist)))
511                     ;; Put back NEXTCHAR so that we can read it normally.
512                     (t (unread-char nextchar stream)))))
513       ;; Next thing is not an isolated dot.
514       (let ((listobj (read-maybe-nothing stream firstchar)))
515         ;; allows the possibility that a comment was read
516         (when listobj
517               (rplacd listtail listobj)
518               (setq listtail listobj))))))
519
520 (defun read-after-dot (stream firstchar)
521   ;; FIRSTCHAR is non-whitespace!
522   (let ((lastobj ()))
523     (do ((char firstchar (flush-whitespace stream)))
524         ((char= char #\) )
525          (%reader-error stream "Nothing appears after . in list."))
526       ;; See whether there's something there.
527       (setq lastobj (read-maybe-nothing stream char))
528       (when lastobj (return t)))
529     ;; At least one thing appears after the dot.
530     ;; Check for more than one thing following dot.
531     (do ((lastchar (flush-whitespace stream)
532                    (flush-whitespace stream)))
533         ((char= lastchar #\) ) lastobj) ;success!
534       ;; Try reading virtual whitespace.
535       (if (read-maybe-nothing stream lastchar)
536           (%reader-error stream "More than one object follows . in list.")))))
537
538 (defun read-string (stream closech)
539   ;; This accumulates chars until it sees same char that invoked it.
540   ;; For a very long string, this could end up bloating the read buffer.
541   (reset-read-buffer)
542   (let ((stream (in-synonym-of stream)))
543     (if (ansi-stream-p stream)
544         (prepare-for-fast-read-char stream
545           (do ((char (fast-read-char t) (fast-read-char t)))
546               ((char= char closech)
547                (done-with-fast-read-char))
548             (if (escapep char) (setq char (fast-read-char t)))
549             (ouch-read-buffer char)))
550         ;; FUNDAMENTAL-STREAM
551         (do ((char (stream-read-char stream) (stream-read-char stream)))
552             ((or (eq char :eof) (char= char closech))
553              (if (eq char :eof)
554                  (error 'end-of-file :stream stream)))
555           (when (escapep char)
556             (setq char (stream-read-char stream))
557             (if (eq char :eof)
558                 (error 'end-of-file :stream stream)))
559           (ouch-read-buffer char))))
560   (read-buffer-to-string))
561
562 (defun read-right-paren (stream ignore)
563   (declare (ignore ignore))
564   (%reader-error stream "unmatched close parenthesis"))
565
566 ;;; Read from the stream up to the next delimiter. Leave the resulting
567 ;;; token in *READ-BUFFER*, and return two values:
568 ;;; -- a list of the escaped character positions, and
569 ;;; -- The position of the first package delimiter (or NIL).
570 (defun internal-read-extended-token (stream firstchar escape-firstchar)
571   (reset-read-buffer)
572   (let ((escapes '()))
573     (when escape-firstchar
574       (push *ouch-ptr* escapes)
575       (ouch-read-buffer firstchar)
576       (setq firstchar (read-char stream nil *eof-object*)))
577   (do ((char firstchar (read-char stream nil *eof-object*))
578        (colon nil))
579       ((cond ((eofp char) t)
580              ((token-delimiterp char)
581               (unread-char char stream)
582               t)
583              (t nil))
584        (values escapes colon))
585     (cond ((escapep char)
586            ;; It can't be a number, even if it's 1\23.
587            ;; Read next char here, so it won't be casified.
588            (push *ouch-ptr* escapes)
589            (let ((nextchar (read-char stream nil *eof-object*)))
590              (if (eofp nextchar)
591                  (reader-eof-error stream "after escape character")
592                  (ouch-read-buffer nextchar))))
593           ((multiple-escape-p char)
594            ;; Read to next multiple-escape, escaping single chars
595            ;; along the way.
596            (loop
597              (let ((ch (read-char stream nil *eof-object*)))
598                (cond
599                 ((eofp ch)
600                  (reader-eof-error stream "inside extended token"))
601                 ((multiple-escape-p ch) (return))
602                 ((escapep ch)
603                  (let ((nextchar (read-char stream nil *eof-object*)))
604                    (cond ((eofp nextchar)
605                           (reader-eof-error stream "after escape character"))
606                          (t
607                           (push *ouch-ptr* escapes)
608                           (ouch-read-buffer nextchar)))))
609                 (t
610                  (push *ouch-ptr* escapes)
611                  (ouch-read-buffer ch))))))
612           (t
613            (when (and (constituentp char)
614                         (eql (get-secondary-attribute char)
615                              +char-attr-package-delimiter+)
616                       (not colon))
617              (setq colon *ouch-ptr*))
618            (ouch-read-buffer char))))))
619 \f
620 ;;;; character classes
621
622 ;;; Return the character class for CHAR.
623 (defmacro char-class (char attable)
624   `(let ((att (aref ,attable (char-code ,char))))
625      (declare (fixnum att))
626      (if (<= att +char-attr-terminating-macro+)
627          +char-attr-delimiter+
628          att)))
629
630 ;;; Return the character class for CHAR, which might be part of a
631 ;;; rational number.
632 (defmacro char-class2 (char attable)
633   `(let ((att (aref ,attable (char-code ,char))))
634      (declare (fixnum att))
635      (if (<= att +char-attr-terminating-macro+)
636          +char-attr-delimiter+
637          (if (digit-char-p ,char *read-base*)
638              +char-attr-constituent-digit+
639              (if (= att +char-attr-constituent-digit+)
640                  +char-attr-constituent+
641                  att)))))
642
643 ;;; Return the character class for a char which might be part of a
644 ;;; rational or floating number. (Assume that it is a digit if it
645 ;;; could be.)
646 (defmacro char-class3 (char attable)
647   `(let ((att (aref ,attable (char-code ,char))))
648      (declare (fixnum att))
649      (if possibly-rational
650          (setq possibly-rational
651                (or (digit-char-p ,char *read-base*)
652                    (= att +char-attr-constituent-slash+))))
653      (if possibly-float
654          (setq possibly-float
655                (or (digit-char-p ,char 10)
656                    (= att +char-attr-constituent-dot+))))
657      (if (<= att +char-attr-terminating-macro+)
658          +char-attr-delimiter+
659          (if (digit-char-p ,char (max *read-base* 10))
660              (if (digit-char-p ,char *read-base*)
661                  +char-attr-constituent-digit+
662                  +char-attr-constituent+)
663              att))))
664 \f
665 ;;;; token fetching
666
667 (defvar *read-suppress* nil
668   #!+sb-doc
669   "Suppress most interpreting in the reader when T.")
670
671 (defvar *read-base* 10
672   #!+sb-doc
673   "the radix that Lisp reads numbers in")
674 (declaim (type (integer 2 36) *read-base*))
675
676 ;;; Modify the read buffer according to READTABLE-CASE, ignoring
677 ;;; ESCAPES. ESCAPES is a list of the escaped indices, in reverse
678 ;;; order.
679 (defun casify-read-buffer (escapes)
680   (let ((case (readtable-case *readtable*)))
681     (cond
682      ((and (null escapes) (eq case :upcase))
683       (dotimes (i *ouch-ptr*)
684         (setf (schar *read-buffer* i)
685               (char-upcase (schar *read-buffer* i)))))
686      ((eq case :preserve))
687      (t
688       (macrolet ((skip-esc (&body body)
689                    `(do ((i (1- *ouch-ptr*) (1- i))
690                          (escapes escapes))
691                         ((minusp i))
692                       (declare (fixnum i))
693                       (when (or (null escapes)
694                                 (let ((esc (first escapes)))
695                                   (declare (fixnum esc))
696                                   (cond ((< esc i) t)
697                                         (t
698                                          (aver (= esc i))
699                                          (pop escapes)
700                                          nil))))
701                         (let ((ch (schar *read-buffer* i)))
702                           ,@body)))))
703         (flet ((lower-em ()
704                  (skip-esc (setf (schar *read-buffer* i) (char-downcase ch))))
705                (raise-em ()
706                  (skip-esc (setf (schar *read-buffer* i) (char-upcase ch)))))
707           (ecase case
708             (:upcase (raise-em))
709             (:downcase (lower-em))
710             (:invert
711              (let ((all-upper t)
712                    (all-lower t))
713                (skip-esc
714                  (when (both-case-p ch)
715                    (if (upper-case-p ch)
716                        (setq all-lower nil)
717                        (setq all-upper nil))))
718                (cond (all-lower (raise-em))
719                      (all-upper (lower-em))))))))))))
720
721 (defun read-token (stream firstchar)
722   #!+sb-doc
723   "This function is just an fsm that recognizes numbers and symbols."
724   ;; Check explicitly whether FIRSTCHAR has an entry for
725   ;; NON-TERMINATING in CHARACTER-ATTRIBUTE-TABLE and
726   ;; READ-DOT-NUMBER-SYMBOL in CMT. Report an error if these are
727   ;; violated. (If we called this, we want something that is a
728   ;; legitimate token!) Read in the longest possible string satisfying
729   ;; the Backus-Naur form for "unqualified-token". Leave the result in
730   ;; the *READ-BUFFER*. Return next char after token (last char read).
731   (when *read-suppress*
732     (internal-read-extended-token stream firstchar nil)
733     (return-from read-token nil))
734   (let ((attribute-table (character-attribute-table *readtable*))
735         (package-designator nil)
736         (colons 0)
737         (possibly-rational t)
738         (possibly-float t)
739         (escapes ()))
740     (reset-read-buffer)
741     (prog ((char firstchar))
742       (case (char-class3 char attribute-table)
743         (#.+char-attr-constituent-sign+ (go SIGN))
744         (#.+char-attr-constituent-digit+ (go LEFTDIGIT))
745         (#.+char-attr-constituent-dot+ (go FRONTDOT))
746         (#.+char-attr-escape+ (go ESCAPE))
747         (#.+char-attr-package-delimiter+ (go COLON))
748         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
749         ;; can't have eof, whitespace, or terminating macro as first char!
750         (t (go SYMBOL)))
751      SIGN ; saw "sign"
752       (ouch-read-buffer char)
753       (setq char (read-char stream nil nil))
754       (unless char (go RETURN-SYMBOL))
755       (setq possibly-rational t
756             possibly-float t)
757       (case (char-class3 char attribute-table)
758         (#.+char-attr-constituent-digit+ (go LEFTDIGIT))
759         (#.+char-attr-constituent-dot+ (go SIGNDOT))
760         (#.+char-attr-escape+ (go ESCAPE))
761         (#.+char-attr-package-delimiter+ (go COLON))
762         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))        
763         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
764         (t (go SYMBOL)))
765      LEFTDIGIT ; saw "[sign] {digit}+"
766       (ouch-read-buffer char)
767       (setq char (read-char stream nil nil))
768       (unless char (return (make-integer)))
769       (case (char-class3 char attribute-table)
770         (#.+char-attr-constituent-digit+ (go LEFTDIGIT))
771         (#.+char-attr-constituent-dot+ (if possibly-float
772                                            (go MIDDLEDOT)
773                                            (go SYMBOL)))
774         (#.+char-attr-constituent-expt+ (go EXPONENT))
775         (#.+char-attr-constituent-slash+ (if possibly-rational
776                                              (go RATIO)
777                                              (go SYMBOL)))
778         (#.+char-attr-delimiter+ (unread-char char stream)
779                                  (return (make-integer)))
780         (#.+char-attr-escape+ (go ESCAPE))
781         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
782         (#.+char-attr-package-delimiter+ (go COLON))
783         (t (go SYMBOL)))
784      MIDDLEDOT ; saw "[sign] {digit}+ dot"
785       (ouch-read-buffer char)
786       (setq char (read-char stream nil nil))
787       (unless char (return (let ((*read-base* 10))
788                              (make-integer))))
789       (case (char-class char attribute-table)
790         (#.+char-attr-constituent-digit+ (go RIGHTDIGIT))
791         (#.+char-attr-constituent-expt+ (go EXPONENT))
792         (#.+char-attr-delimiter+
793          (unread-char char stream)
794          (return (let ((*read-base* 10))
795                    (make-integer))))
796         (#.+char-attr-escape+ (go ESCAPE))
797         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
798         (#.+char-attr-package-delimiter+ (go COLON))
799         (t (go SYMBOL)))
800      RIGHTDIGIT ; saw "[sign] {digit}* dot {digit}+"
801       (ouch-read-buffer char)
802       (setq char (read-char stream nil nil))
803       (unless char (return (make-float)))
804       (case (char-class char attribute-table)
805         (#.+char-attr-constituent-digit+ (go RIGHTDIGIT))
806         (#.+char-attr-constituent-expt+ (go EXPONENT))
807         (#.+char-attr-delimiter+
808          (unread-char char stream)
809          (return (make-float)))
810         (#.+char-attr-escape+ (go ESCAPE))
811         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
812         (#.+char-attr-package-delimiter+ (go COLON))
813         (t (go SYMBOL)))
814      SIGNDOT ; saw "[sign] dot"
815       (ouch-read-buffer char)
816       (setq char (read-char stream nil nil))
817       (unless char (go RETURN-SYMBOL))
818       (case (char-class char attribute-table)
819         (#.+char-attr-constituent-digit+ (go RIGHTDIGIT))
820         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
821         (#.+char-attr-escape+ (go ESCAPE))
822         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
823         (t (go SYMBOL)))
824      FRONTDOT ; saw "dot"
825       (ouch-read-buffer char)
826       (setq char (read-char stream nil nil))
827       (unless char (%reader-error stream "dot context error"))
828       (case (char-class char attribute-table)
829         (#.+char-attr-constituent-digit+ (go RIGHTDIGIT))
830         (#.+char-attr-constituent-dot+ (go DOTS))
831         (#.+char-attr-delimiter+  (%reader-error stream "dot context error"))
832         (#.+char-attr-escape+ (go ESCAPE))
833         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
834         (#.+char-attr-package-delimiter+ (go COLON))
835         (t (go SYMBOL)))
836      EXPONENT
837       (ouch-read-buffer char)
838       (setq char (read-char stream nil nil))
839       (unless char (go RETURN-SYMBOL))
840       (case (char-class char attribute-table)
841         (#.+char-attr-constituent-sign+ (go EXPTSIGN))
842         (#.+char-attr-constituent-digit+ (go EXPTDIGIT))
843         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
844         (#.+char-attr-escape+ (go ESCAPE))
845         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
846         (#.+char-attr-package-delimiter+ (go COLON))
847         (t (go SYMBOL)))
848      EXPTSIGN ; got to EXPONENT, and saw a sign character
849       (ouch-read-buffer char)
850       (setq char (read-char stream nil nil))
851       (unless char (go RETURN-SYMBOL))
852       (case (char-class char attribute-table)
853         (#.+char-attr-constituent-digit+ (go EXPTDIGIT))
854         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
855         (#.+char-attr-escape+ (go ESCAPE))
856         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
857         (#.+char-attr-package-delimiter+ (go COLON))
858         (t (go SYMBOL)))
859      EXPTDIGIT ; got to EXPONENT, saw "[sign] {digit}+"
860       (ouch-read-buffer char)
861       (setq char (read-char stream nil nil))
862       (unless char (return (make-float)))
863       (case (char-class char attribute-table)
864         (#.+char-attr-constituent-digit+ (go EXPTDIGIT))
865         (#.+char-attr-delimiter+
866          (unread-char char stream)
867          (return (make-float)))
868         (#.+char-attr-escape+ (go ESCAPE))
869         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
870         (#.+char-attr-package-delimiter+ (go COLON))
871         (t (go SYMBOL)))
872      RATIO ; saw "[sign] {digit}+ slash"
873       (ouch-read-buffer char)
874       (setq char (read-char stream nil nil))
875       (unless char (go RETURN-SYMBOL))
876       (case (char-class2 char attribute-table)
877         (#.+char-attr-constituent-digit+ (go RATIODIGIT))
878         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
879         (#.+char-attr-escape+ (go ESCAPE))
880         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
881         (#.+char-attr-package-delimiter+ (go COLON))
882         (t (go SYMBOL)))
883      RATIODIGIT ; saw "[sign] {digit}+ slash {digit}+"
884       (ouch-read-buffer char)
885       (setq char (read-char stream nil nil))
886       (unless char (return (make-ratio)))
887       (case (char-class2 char attribute-table)
888         (#.+char-attr-constituent-digit+ (go RATIODIGIT))
889         (#.+char-attr-delimiter+
890          (unread-char char stream)
891          (return (make-ratio)))
892         (#.+char-attr-escape+ (go ESCAPE))
893         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
894         (#.+char-attr-package-delimiter+ (go COLON))
895         (t (go SYMBOL)))
896      DOTS ; saw "dot {dot}+"
897       (ouch-read-buffer char)
898       (setq char (read-char stream nil nil))
899       (unless char (%reader-error stream "too many dots"))
900       (case (char-class char attribute-table)
901         (#.+char-attr-constituent-dot+ (go DOTS))
902         (#.+char-attr-delimiter+
903          (unread-char char stream)
904          (%reader-error stream "too many dots"))
905         (#.+char-attr-escape+ (go ESCAPE))
906         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
907         (#.+char-attr-package-delimiter+ (go COLON))
908         (t (go SYMBOL)))
909      SYMBOL ; not a dot, dots, or number
910       (let ((stream (in-synonym-of stream)))
911         (if (ansi-stream-p stream)
912             (prepare-for-fast-read-char stream
913               (prog ()
914                SYMBOL-LOOP
915                (ouch-read-buffer char)
916                (setq char (fast-read-char nil nil))
917                (unless char (go RETURN-SYMBOL))
918                (case (char-class char attribute-table)
919                  (#.+char-attr-escape+ (done-with-fast-read-char)
920                                        (go ESCAPE))
921                  (#.+char-attr-delimiter+ (done-with-fast-read-char)
922                                           (unread-char char stream)
923                                           (go RETURN-SYMBOL))
924                  (#.+char-attr-multiple-escape+ (done-with-fast-read-char)
925                                                 (go MULT-ESCAPE))
926                  (#.+char-attr-package-delimiter+ (done-with-fast-read-char)
927                                                   (go COLON))
928                  (t (go SYMBOL-LOOP)))))
929             ;; fundamental-stream
930             (prog ()
931              SYMBOL-LOOP
932              (ouch-read-buffer char)
933              (setq char (stream-read-char stream))
934              (when (eq char :eof) (go RETURN-SYMBOL))
935              (case (char-class char attribute-table)
936                (#.+char-attr-escape+ (go ESCAPE))
937                (#.+char-attr-delimiter+ (stream-unread-char stream char)
938                             (go RETURN-SYMBOL))
939                (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
940                (#.+char-attr-package-delimiter+ (go COLON))
941                (t (go SYMBOL-LOOP))))))
942      ESCAPE ; saw an escape
943       ;; Don't put the escape in the read buffer.
944       ;; READ-NEXT CHAR, put in buffer (no case conversion).
945       (let ((nextchar (read-char stream nil nil)))
946         (unless nextchar
947           (reader-eof-error stream "after escape character"))
948         (push *ouch-ptr* escapes)
949         (ouch-read-buffer nextchar))
950       (setq char (read-char stream nil nil))
951       (unless char (go RETURN-SYMBOL))
952       (case (char-class char attribute-table)
953         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
954         (#.+char-attr-escape+ (go ESCAPE))
955         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
956         (#.+char-attr-package-delimiter+ (go COLON))
957         (t (go SYMBOL)))
958       MULT-ESCAPE
959       (do ((char (read-char stream t) (read-char stream t)))
960           ((multiple-escape-p char))
961         (if (escapep char) (setq char (read-char stream t)))
962         (push *ouch-ptr* escapes)
963         (ouch-read-buffer char))
964       (setq char (read-char stream nil nil))
965       (unless char (go RETURN-SYMBOL))
966       (case (char-class char attribute-table)
967         (#.+char-attr-delimiter+ (unread-char char stream) (go RETURN-SYMBOL))
968         (#.+char-attr-escape+ (go ESCAPE))
969         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
970         (#.+char-attr-package-delimiter+ (go COLON))
971         (t (go SYMBOL)))
972       COLON
973       (casify-read-buffer escapes)
974       (unless (zerop colons)
975         (%reader-error stream "too many colons in ~S"
976                       (read-buffer-to-string)))
977       (setq colons 1)
978       (setq package-designator
979             (if (plusp *ouch-ptr*)
980                 ;; FIXME: It seems inefficient to cons up a package
981                 ;; designator string every time we read a symbol with an
982                 ;; explicit package prefix. Perhaps we could implement
983                 ;; a FIND-PACKAGE* function analogous to INTERN*
984                 ;; and friends?
985                 (read-buffer-to-string)
986                 *keyword-package*))
987       (reset-read-buffer)
988       (setq escapes ())
989       (setq char (read-char stream nil nil))
990       (unless char (reader-eof-error stream "after reading a colon"))
991       (case (char-class char attribute-table)
992         (#.+char-attr-delimiter+
993          (unread-char char stream)
994          (%reader-error stream
995                         "illegal terminating character after a colon: ~S"
996                         char))
997         (#.+char-attr-escape+ (go ESCAPE))
998         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
999         (#.+char-attr-package-delimiter+ (go INTERN))
1000         (t (go SYMBOL)))
1001       INTERN
1002       (setq colons 2)
1003       (setq char (read-char stream nil nil))
1004       (unless char
1005         (reader-eof-error stream "after reading a colon"))
1006       (case (char-class char attribute-table)
1007         (#.+char-attr-delimiter+
1008          (unread-char char stream)
1009          (%reader-error stream
1010                         "illegal terminating character after a colon: ~S"
1011                         char))
1012         (#.+char-attr-escape+ (go ESCAPE))
1013         (#.+char-attr-multiple-escape+ (go MULT-ESCAPE))
1014         (#.+char-attr-package-delimiter+
1015          (%reader-error stream
1016                         "too many colons after ~S name"
1017                         package-designator))
1018         (t (go SYMBOL)))
1019       RETURN-SYMBOL
1020       (casify-read-buffer escapes)
1021       (let ((found (if package-designator
1022                        (find-package package-designator)
1023                        (sane-package))))
1024         (unless found
1025           (error 'reader-package-error :stream stream
1026                  :format-arguments (list package-designator)
1027                  :format-control "package ~S not found"))
1028
1029         (if (or (zerop colons) (= colons 2) (eq found *keyword-package*))
1030             (return (intern* *read-buffer* *ouch-ptr* found))
1031             (multiple-value-bind (symbol test)
1032                 (find-symbol* *read-buffer* *ouch-ptr* found)
1033               (when (eq test :external) (return symbol))
1034               (let ((name (read-buffer-to-string)))
1035                 (with-simple-restart (continue "Use symbol anyway.")
1036                   (error 'reader-package-error :stream stream
1037                          :format-arguments (list name (package-name found))
1038                          :format-control
1039                          (if test
1040                              "The symbol ~S is not external in the ~A package."
1041                              "Symbol ~S not found in the ~A package.")))
1042                 (return (intern name found)))))))))
1043
1044 ;;; for semi-external use:
1045 ;;;
1046 ;;; For semi-external use: Return 3 values: the string for the token,
1047 ;;; a flag for whether there was an escape char, and the position of
1048 ;;; any package delimiter.
1049 (defun read-extended-token (stream &optional (*readtable* *readtable*))
1050   (let ((first-char (read-char stream nil nil t)))
1051     (cond (first-char
1052            (multiple-value-bind (escapes colon)
1053                (internal-read-extended-token stream first-char nil)
1054              (casify-read-buffer escapes)
1055              (values (read-buffer-to-string) (not (null escapes)) colon)))
1056           (t
1057            (values "" nil nil)))))
1058
1059 ;;; for semi-external use:
1060 ;;;
1061 ;;; Read an extended token with the first character escaped. Return
1062 ;;; the string for the token.
1063 (defun read-extended-token-escaped (stream &optional (*readtable* *readtable*))
1064   (let ((first-char (read-char stream nil nil)))
1065     (cond (first-char
1066             (let ((escapes (internal-read-extended-token stream first-char t)))
1067               (casify-read-buffer escapes)
1068               (read-buffer-to-string)))
1069           (t
1070             (reader-eof-error stream "after escape")))))
1071 \f
1072 ;;;; number-reading functions
1073
1074 (defmacro digit* nil
1075   `(do ((ch char (inch-read-buffer)))
1076        ((or (eofp ch) (not (digit-char-p ch))) (setq char ch))
1077      ;; Report if at least one digit is seen.
1078      (setq one-digit t)))
1079
1080 (defmacro exponent-letterp (letter)
1081   `(memq ,letter '(#\E #\S #\F #\L #\D #\e #\s #\f #\l #\d)))
1082
1083 ;;; FIXME: It would be cleaner to have these generated automatically
1084 ;;; by compile-time code instead of having them hand-created like
1085 ;;; this. The !COLD-INIT-INTEGER-READER code below should be resurrected
1086 ;;; and tested.
1087 (defvar *integer-reader-safe-digits*
1088   #(nil nil
1089     26 17 13 11 10 9 8 8 8 7 7 7 7 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 5 5 5 5)
1090   #!+sb-doc
1091   "the mapping of base to 'safe' number of digits to read for a fixnum")
1092 (defvar *integer-reader-base-power*
1093   #(nil nil
1094     67108864 129140163 67108864 48828125 60466176 40353607
1095     16777216 43046721 100000000 19487171 35831808 62748517 105413504 11390625
1096     16777216 24137569 34012224 47045881 64000000 85766121 113379904 6436343
1097     7962624 9765625 11881376 14348907 17210368 20511149 24300000 28629151
1098     33554432 39135393 45435424 52521875 60466176)
1099   #!+sb-doc
1100   "the largest fixnum power of the base for MAKE-INTEGER")
1101 (declaim (simple-vector *integer-reader-safe-digits*
1102                         *integer-reader-base-power*))
1103 #|
1104 (defun !cold-init-integer-reader ()
1105   (do ((base 2 (1+ base)))
1106       ((> base 36))
1107     (let ((digits
1108           (do ((fix (truncate most-positive-fixnum base)
1109                     (truncate fix base))
1110                (digits 0 (1+ digits)))
1111               ((zerop fix) digits))))
1112       (setf (aref *integer-reader-safe-digits* base)
1113             digits
1114             (aref *integer-reader-base-power* base)
1115             (expt base digits)))))
1116 |#
1117
1118 (defun make-integer ()
1119   #!+sb-doc
1120   "Minimizes bignum-fixnum multiplies by reading a 'safe' number of digits,
1121   then multiplying by a power of the base and adding."
1122   (let* ((base *read-base*)
1123          (digits-per (aref *integer-reader-safe-digits* base))
1124          (base-power (aref *integer-reader-base-power* base))
1125          (negativep nil)
1126          (number 0))
1127     (declare (type index digits-per base-power))
1128     (read-unwind-read-buffer)
1129     (let ((char (inch-read-buffer)))
1130       (cond ((char= char #\-)
1131              (setq negativep t))
1132             ((char= char #\+))
1133             (t (unread-buffer))))
1134     (loop
1135      (let ((num 0))
1136        (declare (type index num))
1137        (dotimes (digit digits-per)
1138          (let* ((ch (inch-read-buffer)))
1139            (cond ((or (eofp ch) (char= ch #\.))
1140                   (return-from make-integer
1141                                (let ((res
1142                                       (if (zerop number) num
1143                                           (+ num (* number
1144                                                     (expt base digit))))))
1145                                  (if negativep (- res) res))))
1146                  (t (setq num (+ (digit-char-p ch base)
1147                                  (the index (* num base))))))))
1148        (setq number (+ num (* number base-power)))))))
1149
1150 (defun make-float ()
1151   ;; Assume that the contents of *read-buffer* are a legal float, with nothing
1152   ;; else after it.
1153   (read-unwind-read-buffer)
1154   (let ((negative-fraction nil)
1155         (number 0)
1156         (divisor 1)
1157         (negative-exponent nil)
1158         (exponent 0)
1159         (float-char ())
1160         (char (inch-read-buffer)))
1161     (if (cond ((char= char #\+) t)
1162               ((char= char #\-) (setq negative-fraction t)))
1163         ;; Flush it.
1164         (setq char (inch-read-buffer)))
1165     ;; Read digits before the dot.
1166     (do* ((ch char (inch-read-buffer))
1167           (dig (digit-char-p ch) (digit-char-p ch)))
1168          ((not dig) (setq char ch))
1169       (setq number (+ (* number 10) dig)))
1170     ;; Deal with the dot, if it's there.
1171     (when (char= char #\.)
1172       (setq char (inch-read-buffer))
1173       ;; Read digits after the dot.
1174       (do* ((ch char (inch-read-buffer))
1175             (dig (and (not (eofp ch)) (digit-char-p ch))
1176                  (and (not (eofp ch)) (digit-char-p ch))))
1177            ((not dig) (setq char ch))
1178         (setq divisor (* divisor 10))
1179         (setq number (+ (* number 10) dig))))
1180     ;; Is there an exponent letter?
1181     (cond ((eofp char)
1182            ;; If not, we've read the whole number.
1183            (let ((num (make-float-aux number divisor
1184                                       *read-default-float-format*)))
1185              (return-from make-float (if negative-fraction (- num) num))))
1186           ((exponent-letterp char)
1187            (setq float-char char)
1188            ;; Build exponent.
1189            (setq char (inch-read-buffer))
1190            ;; Check leading sign.
1191            (if (cond ((char= char #\+) t)
1192                      ((char= char #\-) (setq negative-exponent t)))
1193                ;; Flush sign.
1194                (setq char (inch-read-buffer)))
1195            ;; Read digits for exponent.
1196            (do* ((ch char (inch-read-buffer))
1197                  (dig (and (not (eofp ch)) (digit-char-p ch))
1198                       (and (not (eofp ch)) (digit-char-p ch))))
1199                 ((not dig)
1200                  (setq exponent (if negative-exponent (- exponent) exponent)))
1201              (setq exponent (+ (* exponent 10) dig)))
1202            ;; Generate and return the float, depending on FLOAT-CHAR:
1203            (let* ((float-format (case (char-upcase float-char)
1204                                   (#\E *read-default-float-format*)
1205                                   (#\S 'short-float)
1206                                   (#\F 'single-float)
1207                                   (#\D 'double-float)
1208                                   (#\L 'long-float)))
1209                   num)
1210              ;; Raymond Toy writes: We need to watch out if the
1211              ;; exponent is too small or too large. We add enough to
1212              ;; EXPONENT to make it within range and scale NUMBER
1213              ;; appropriately. This should avoid any unnecessary
1214              ;; underflow or overflow problems.
1215              (multiple-value-bind (min-expo max-expo)
1216                  ;; FIXME: These forms are broken w.r.t.
1217                  ;; cross-compilation portability, as the
1218                  ;; cross-compiler will call the host's LOG function
1219                  ;; while attempting to constant-fold. Maybe some sort
1220                  ;; of load-time-form magic could be used instead?
1221                  (case float-format
1222                    (short-float
1223                     (values
1224                      (log sb!xc:least-positive-normalized-short-float 10s0)
1225                      (log sb!xc:most-positive-short-float 10s0)))
1226                    (single-float
1227                     (values
1228                      (log sb!xc:least-positive-normalized-single-float 10f0)
1229                      (log sb!xc:most-positive-single-float 10f0)))
1230                    (double-float
1231                     (values
1232                      (log sb!xc:least-positive-normalized-double-float 10d0)
1233                      (log sb!xc:most-positive-double-float 10d0)))
1234                    (long-float
1235                     (values
1236                      (log sb!xc:least-positive-normalized-long-float 10L0)
1237                      (log sb!xc:most-positive-long-float 10L0))))
1238                (let ((correction (cond ((<= exponent min-expo)
1239                                         (ceiling (- min-expo exponent)))
1240                                        ((>= exponent max-expo)
1241                                         (floor (- max-expo exponent)))
1242                                        (t
1243                                         0))))
1244                  (incf exponent correction)
1245                  (setf number (/ number (expt 10 correction)))
1246                  (setq num (make-float-aux number divisor float-format))
1247                  (setq num (* num (expt 10 exponent)))
1248                  (return-from make-float (if negative-fraction
1249                                              (- num)
1250                                              num))))))
1251           ;; should never happen
1252           (t (bug "bad fallthrough in floating point reader")))))
1253
1254 (defun make-float-aux (number divisor float-format)
1255   (coerce (/ number divisor) float-format))
1256
1257 (defun make-ratio ()
1258   ;; Assume *READ-BUFFER* contains a legal ratio. Build the number from
1259   ;; the string.
1260   ;;
1261   ;; Look for optional "+" or "-".
1262   (let ((numerator 0) (denominator 0) (char ()) (negative-number nil))
1263     (read-unwind-read-buffer)
1264     (setq char (inch-read-buffer))
1265     (cond ((char= char #\+)
1266            (setq char (inch-read-buffer)))
1267           ((char= char #\-)
1268            (setq char (inch-read-buffer))
1269            (setq negative-number t)))
1270     ;; Get numerator.
1271     (do* ((ch char (inch-read-buffer))
1272           (dig (digit-char-p ch *read-base*)
1273                (digit-char-p ch *read-base*)))
1274          ((not dig))
1275          (setq numerator (+ (* numerator *read-base*) dig)))
1276     ;; Get denominator.
1277     (do* ((ch (inch-read-buffer) (inch-read-buffer))
1278           (dig ()))
1279          ((or (eofp ch) (not (setq dig (digit-char-p ch *read-base*)))))
1280          (setq denominator (+ (* denominator *read-base*) dig)))
1281     (let ((num (/ numerator denominator)))
1282       (if negative-number (- num) num))))
1283 \f
1284 ;;;; cruft for dispatch macros
1285
1286 (defun make-char-dispatch-table ()
1287   (make-array char-code-limit :initial-element #'dispatch-char-error))
1288
1289 (defun dispatch-char-error (stream sub-char ignore)
1290   (declare (ignore ignore))
1291   (if *read-suppress*
1292       (values)
1293       (%reader-error stream "no dispatch function defined for ~S" sub-char)))
1294
1295 (defun make-dispatch-macro-character (char &optional
1296                                            (non-terminating-p nil)
1297                                            (rt *readtable*))
1298   #!+sb-doc
1299   "Cause CHAR to become a dispatching macro character in readtable (which
1300    defaults to the current readtable). If NON-TERMINATING-P, the char will
1301    be non-terminating."
1302   (set-macro-character char #'read-dispatch-char non-terminating-p rt)
1303   (let* ((dalist (dispatch-tables rt))
1304          (dtable (cdr (find char dalist :test #'char= :key #'car))))
1305     (cond (dtable
1306            (error "The dispatch character ~S already exists." char))
1307           (t
1308            (setf (dispatch-tables rt)
1309                  (push (cons char (make-char-dispatch-table)) dalist)))))
1310   t)
1311
1312 (defun set-dispatch-macro-character (disp-char sub-char function
1313                                                &optional (rt *readtable*))
1314   #!+sb-doc
1315   "Cause FUNCTION to be called whenever the reader reads DISP-CHAR
1316    followed by SUB-CHAR."
1317   ;; Get the dispatch char for macro (error if not there), diddle
1318   ;; entry for sub-char.
1319   (when (digit-char-p sub-char)
1320     (error "SUB-CHAR must not be a decimal digit: ~S" sub-char))
1321   (let* ((sub-char (char-upcase sub-char))
1322          (rt (or rt *standard-readtable*))
1323          (dpair (find disp-char (dispatch-tables rt)
1324                       :test #'char= :key #'car)))
1325     (if dpair
1326         (setf (elt (the simple-vector (cdr dpair))
1327                    (char-code sub-char))
1328               (coerce function 'function))
1329         (error "~S is not a dispatch char." disp-char))))
1330
1331 (defun get-dispatch-macro-character (disp-char sub-char
1332                                      &optional (rt *readtable*))
1333   #!+sb-doc
1334   "Return the macro character function for SUB-CHAR under DISP-CHAR
1335    or NIL if there is no associated function."
1336   (let* ((sub-char (char-upcase sub-char))
1337          (rt (or rt *standard-readtable*))
1338          (dpair (find disp-char (dispatch-tables rt)
1339                       :test #'char= :key #'car)))
1340     (if dpair
1341         (let ((dispatch-fun (elt (the simple-vector (cdr dpair))
1342                                  (char-code sub-char))))
1343           ;; Digits are also initialized in a dispatch table to
1344           ;; #'dispatch-char-error; READ-DISPATCH-CHAR handles them
1345           ;; separately. - CSR, 2002-04-12
1346           (if (eq dispatch-fun #'dispatch-char-error)
1347               nil
1348               dispatch-fun))
1349         (error "~S is not a dispatch char." disp-char))))
1350
1351 (defun read-dispatch-char (stream char)
1352   ;; Read some digits.
1353   (let ((numargp nil)
1354         (numarg 0)
1355         (sub-char ()))
1356     (do* ((ch (read-char stream nil *eof-object*)
1357               (read-char stream nil *eof-object*))
1358           (dig ()))
1359          ((or (eofp ch)
1360               (not (setq dig (digit-char-p ch))))
1361           ;; Take care of the extra char.
1362           (if (eofp ch)
1363               (reader-eof-error stream "inside dispatch character")
1364               (setq sub-char (char-upcase ch))))
1365       (setq numargp t)
1366       (setq numarg (+ (* numarg 10) dig)))
1367     ;; Look up the function and call it.
1368     (let ((dpair (find char (dispatch-tables *readtable*)
1369                        :test #'char= :key #'car)))
1370       (if dpair
1371           (funcall (the function
1372                         (elt (the simple-vector (cdr dpair))
1373                              (char-code sub-char)))
1374                    stream sub-char (if numargp numarg nil))
1375           (%reader-error stream "no dispatch table for dispatch char")))))
1376 \f
1377 ;;;; READ-FROM-STRING
1378
1379 ;;; FIXME: Is it really worth keeping this pool?
1380 (defvar *read-from-string-spares* ()
1381   #!+sb-doc
1382   "A resource of string streams for Read-From-String.")
1383
1384 (defun read-from-string (string &optional eof-error-p eof-value
1385                                 &key (start 0) end
1386                                 preserve-whitespace)
1387   #!+sb-doc
1388   "The characters of string are successively given to the lisp reader
1389    and the lisp object built by the reader is returned. Macro chars
1390    will take effect."
1391   (declare (string string))
1392   (with-array-data ((string string)
1393                     (start start)
1394                     (end (or end (length string))))
1395     (unless *read-from-string-spares*
1396       (push (internal-make-string-input-stream "" 0 0)
1397             *read-from-string-spares*))
1398     (let ((stream (pop *read-from-string-spares*)))
1399       (setf (string-input-stream-string stream) string)
1400       (setf (string-input-stream-current stream) start)
1401       (setf (string-input-stream-end stream) end)
1402       (unwind-protect
1403           (values (if preserve-whitespace
1404                       (read-preserving-whitespace stream eof-error-p eof-value)
1405                       (read stream eof-error-p eof-value))
1406                   (string-input-stream-current stream))
1407         (push stream *read-from-string-spares*)))))
1408 \f
1409 ;;;; PARSE-INTEGER
1410
1411 (defun parse-integer (string &key (start 0) end (radix 10) junk-allowed)
1412   #!+sb-doc
1413   "Examine the substring of string delimited by start and end
1414   (default to the beginning and end of the string)  It skips over
1415   whitespace characters and then tries to parse an integer. The
1416   radix parameter must be between 2 and 36."
1417   (with-array-data ((string string)
1418                     (start start)
1419                     (end (or end (length string))))
1420     (let ((index (do ((i start (1+ i)))
1421                      ((= i end)
1422                       (if junk-allowed
1423                           (return-from parse-integer (values nil end))
1424                           (error "no non-whitespace characters in number")))
1425                    (declare (fixnum i))
1426                    (unless (whitespacep (char string i)) (return i))))
1427           (minusp nil)
1428           (found-digit nil)
1429           (result 0))
1430       (declare (fixnum index))
1431       (let ((char (char string index)))
1432         (cond ((char= char #\-)
1433                (setq minusp t)
1434                (incf index))
1435               ((char= char #\+)
1436                (incf index))))
1437       (loop
1438         (when (= index end) (return nil))
1439         (let* ((char (char string index))
1440                (weight (digit-char-p char radix)))
1441           (cond (weight
1442                  (setq result (+ weight (* result radix))
1443                        found-digit t))
1444                 (junk-allowed (return nil))
1445                 ((whitespacep char)
1446                  (do ((jndex (1+ index) (1+ jndex)))
1447                      ((= jndex end))
1448                    (declare (fixnum jndex))
1449                    (unless (whitespacep (char string jndex))
1450                      (error "junk in string ~S" string)))
1451                  (return nil))
1452                 (t
1453                  (error "junk in string ~S" string))))
1454         (incf index))
1455       (values
1456        (if found-digit
1457            (if minusp (- result) result)
1458            (if junk-allowed
1459                nil
1460                (error "no digits in string ~S" string)))
1461        index))))
1462 \f
1463 ;;;; reader initialization code
1464
1465 (defun !reader-cold-init ()
1466   (!cold-init-read-buffer)
1467   (!cold-init-secondary-attribute-table)
1468   (!cold-init-standard-readtable)
1469   ;; FIXME: This was commented out, but should probably be restored.
1470   #+nil (!cold-init-integer-reader))
1471 \f
1472 (def!method print-object ((readtable readtable) stream)
1473   (print-unreadable-object (readtable stream :identity t :type t)))