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