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