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