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