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