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