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