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