*features* support for the reader
[jscl.git] / src / read.lisp
1 ;;; read.lisp --- 
2
3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
6 ;; JSCL is free software: you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation, either version 3 of the
9 ;; License, or (at your option) any later version.
10 ;;
11 ;; JSCL is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;; General Public License for more details.
15 ;;
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
18
19
20 ;;;; Reader
21
22 ;;; The Lisp reader, parse strings and return Lisp objects. The main
23 ;;; entry points are `ls-read' and `ls-read-from-string'.
24
25 ;;; #= / ## implementation
26
27 ;; For now associations label->object are kept in a plist
28 ;; May be it makes sense to use a vector instead if speed
29 ;; is considered a problem with many labelled objects
30 (defvar *labelled-objects* nil)
31
32 (defun new-labelled-objects-table ()
33   (setf *labelled-objects* nil))
34
35 (defun find-labelled-object (id)
36   (assoc id *labelled-objects*))
37
38 (defun add-labelled-object (id value)
39   (push (cons id value) *labelled-objects*))
40
41 ;; A unique value used to mark in the labelled objects
42 ;; table an object that is being constructed
43 ;; (e.g. #1# while reading elements of "#1=(#1# #1# #1#)")
44 (defvar *future-value* (make-symbol "future"))
45
46 ;; A unique value used to mark temporary values that will
47 ;; be replaced when fixups are run.
48 (defvar *fixup-value* (make-symbol "fixup"))
49
50 ;; Fixup locations keeps a list of conses where the CAR
51 ;; is a callable to be called with the value of the object
52 ;; associated to label stored in CDR once reading is completed
53 (defvar *fixup-locations* nil)
54
55 (defun fixup-backrefs ()
56   (while *fixup-locations*
57     (let* ((fixup (pop *fixup-locations*))
58            (callable (car fixup))
59            (cell (find-labelled-object (cdr fixup))))
60       (if cell
61           (funcall callable (cdr cell))
62           (error "Internal error in fixup-backrefs: object #~S# not found"
63                  (cdr fixup))))))
64
65 ;; A function that will need to return a fixup callback
66 ;; for the object that is being read. The returned callback will
67 ;; be called with the result of reading.
68 (defvar *make-fixup-function*
69   (lambda ()
70     (error "Internal error in fixup creation during read")))
71
72 (defun make-string-stream (string)
73   (cons string 0))
74
75 (defun %peek-char (stream)
76   (and (< (cdr stream) (length (car stream)))
77        (char (car stream) (cdr stream))))
78
79 (defun %read-char (stream)
80   (and (< (cdr stream) (length (car stream)))
81        (prog1 (char (car stream) (cdr stream))
82          (rplacd stream (1+ (cdr stream))))))
83
84 (defun whitespacep (ch)
85   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
86
87 (defun skip-whitespaces (stream)
88   (let (ch)
89     (setq ch (%peek-char stream))
90     (while (and ch (whitespacep ch))
91       (%read-char stream)
92       (setq ch (%peek-char stream)))))
93
94 (defun terminalp (ch)
95   (or (null ch) (whitespacep ch) (char= #\" ch) (char= #\) ch) (char= #\( ch)))
96
97 (defun read-until (stream func)
98   (let ((string "")
99         (ch))
100     (setq ch (%peek-char stream))
101     (while (and ch (not (funcall func ch)))
102       (setq string (concat string (string ch)))
103       (%read-char stream)
104       (setq ch (%peek-char stream)))
105     string))
106
107 (defun read-escaped-until (stream func)
108   (let ((string "")
109         (ch (%peek-char stream))
110         (multi-escape nil))
111     (while (and ch (or multi-escape (not (funcall func ch))))
112       (cond
113         ((char= ch #\|)
114          (if multi-escape
115              (setf multi-escape nil)
116              (setf multi-escape t)))
117         ((char= ch #\\)
118          (%read-char stream)
119          (setf ch (%peek-char stream))
120          (setf string (concat string "\\" (string ch))))
121         (t
122          (if multi-escape
123              (setf string (concat string "\\" (string ch)))
124              (setf string (concat string (string ch))))))
125       (%read-char stream)
126       (setf ch (%peek-char stream)))
127     string))
128
129 (defun skip-whitespaces-and-comments (stream)
130   (let (ch)
131     (skip-whitespaces stream)
132     (setq ch (%peek-char stream))
133     (while (and ch (char= ch #\;))
134       (read-until stream (lambda (x) (char= x #\newline)))
135       (skip-whitespaces stream)
136       (setq ch (%peek-char stream)))))
137
138 (defun discard-char (stream expected)
139   (let ((ch (%read-char stream)))
140     (when (null ch)
141       (error "End of file when character ~S was expected." expected))
142     (unless (char= ch expected)
143       (error "Character ~S was found but ~S was expected." ch expected))))
144
145 (defun %read-list (stream &optional (eof-error-p t) eof-value)
146   (skip-whitespaces-and-comments stream)
147   (let ((ch (%peek-char stream)))
148     (cond
149       ((null ch)
150        (error "Unspected EOF"))
151       ((char= ch #\))
152        (discard-char stream #\))
153        nil)
154       (t
155        (let* ((cell (cons nil nil))
156               (*make-fixup-function* (lambda ()
157                                        (lambda (obj)
158                                          (rplaca cell obj))))
159               (eof (gensym))
160               (next (ls-read stream nil eof t)))
161          (rplaca cell next)
162          (skip-whitespaces-and-comments stream)
163          (cond
164            ((eq next eof)
165             (discard-char stream #\))
166             nil)
167            (t
168             (if (char= (%peek-char stream) #\.)
169                 (progn
170                   (discard-char stream #\.)
171                   (if (terminalp (%peek-char stream))
172                       (let ((*make-fixup-function* (lambda ()
173                                                      (lambda (obj)
174                                                        (rplacd cell obj)))))
175                         ;; Dotted pair notation
176                         (rplacd cell (ls-read stream eof-error-p eof-value t))
177                         (skip-whitespaces-and-comments stream)
178                         (let ((ch (%peek-char stream)))
179                           (if (or (null ch) (char= #\) ch))
180                               (discard-char stream #\))
181                               (error "Multiple objects following . in a list"))))
182                       (let ((token (concat "." (read-escaped-until stream #'terminalp))))
183                         (rplacd cell (cons (interpret-token token)
184                                            (%read-list stream eof-error-p eof-value))))))
185                 (rplacd cell (%read-list stream eof-error-p eof-value)))
186             cell)))))))
187
188 (defun read-string (stream)
189   (let ((string "")
190         (ch nil))
191     (setq ch (%read-char stream))
192     (while (not (eql ch #\"))
193       (when (null ch)
194         (error "Unexpected EOF"))
195       (when (eql ch #\\)
196         (setq ch (%read-char stream)))
197       (setq string (concat string (string ch)))
198       (setq ch (%read-char stream)))
199     string))
200
201 (defun read-sharp (stream &optional eof-error-p eof-value)
202   (%read-char stream)
203   (let ((ch (%read-char stream)))
204     (cond
205       ((char= ch #\')
206        (list 'function (ls-read stream eof-error-p eof-value t)))
207       ((char= ch #\()
208        (do ((elements nil)
209             (result nil)
210             (index 0 (1+ index)))
211            ((progn (skip-whitespaces-and-comments stream)
212                    (or (null (%peek-char stream))
213                        (char= (%peek-char stream) #\))))
214               (discard-char stream #\))
215               (setf result (make-array index))
216               (dotimes (i index)
217                 (aset result (decf index) (pop elements)))
218               result)
219          (let* ((ix index) ; Can't just use index: the same var would be captured in all fixups
220                 (*make-fixup-function* (lambda ()
221                                          (lambda (obj)
222                                            (aset result ix obj))))
223                 (eof (gensym))
224                 (value (ls-read stream nil eof t)))
225            (push value elements))))
226       ((char= ch #\:)
227        (make-symbol
228         (unescape-token
229          (string-upcase-noescaped
230           (read-escaped-until stream #'terminalp)))))
231       ((char= ch #\\)
232        (let ((cname
233               (concat (string (%read-char stream))
234                       (read-until stream #'terminalp))))
235          (cond
236            ((string= cname "space") #\space)
237            ((string= cname "tab") #\tab)
238            ((string= cname "newline") #\newline)
239            (t (char cname 0)))))
240       ((or (char= ch #\+)
241            (char= ch #\-))
242        (let ((feature (let ((symbol (ls-read stream eof-error-p eof-value t)))
243                         (unless (symbolp symbol)
244                           (error "Invalid feature ~S" symbol))
245                         (intern (string symbol) "KEYWORD"))))
246          (if (eql (char= ch #\+)
247                   (and (find feature *features*) t))
248               (ls-read stream eof-error-p eof-value t)
249               (prog2 (ls-read stream)
250                   (ls-read stream eof-error-p eof-value t)))))
251       ((and ch (digit-char-p ch))
252        (let ((id (digit-char-p ch)))
253          (while (and (%peek-char stream)
254                      (digit-char-p (%peek-char stream)))
255            (setf id (+ (* id 10) (digit-char-p (%read-char stream)))))
256          (ecase (%peek-char stream)
257            (#\=
258               (%read-char stream)
259               (if (find-labelled-object id)
260                   (error "Duplicated label #~S=" id)
261                   (progn
262                     (add-labelled-object id *future-value*)
263                     (let ((obj (ls-read stream eof-error-p eof-value t)))
264                       ;; FIXME: somehow the more natural
265                       ;;    (setf (cdr (find-labelled-object id)) obj)
266                       ;; doesn't work
267                       (rplacd (find-labelled-object id) obj)
268                       obj))))
269            (#\#
270               (%read-char stream)
271               (let ((cell (find-labelled-object id)))
272                 (if cell
273                     (if (eq (cdr cell) *future-value*)
274                         (progn
275                           (push (cons (funcall *make-fixup-function*)
276                                       id)
277                                 *fixup-locations*)
278                           *fixup-value*)
279                         (cdr cell))
280                     (error "Invalid labelled object #~S#" id)))))))
281       (t
282        (error "Invalid dispatch character after #")))))
283
284 (defun unescape-token (x)
285   (let ((result ""))
286     (dotimes (i (length x))
287       (unless (char= (char x i) #\\)
288         (setq result (concat result (string (char x i))))))
289     result))
290
291 (defun string-upcase-noescaped (s)
292   (let ((result "")
293         (last-escape nil))
294     (dotimes (i (length s))
295       (let ((ch (char s i)))
296         (if last-escape
297            (progn
298               (setf last-escape nil)
299               (setf result (concat result (string ch))))
300             (if (char= ch #\\)
301                 (setf last-escape t)
302                 (setf result (concat result (string-upcase (string ch))))))))
303     result))
304
305 ;;; Parse a string of the form NAME, PACKAGE:NAME or
306 ;;; PACKAGE::NAME and return the name. If the string is of the
307 ;;; form 1) or 3), but the symbol does not exist, it will be created
308 ;;; and interned in that package.
309 (defun read-symbol (string)
310   (let ((size (length string))
311         package name internalp index)
312     (setq index 0)
313     (while (and (< index size)
314                 (not (char= (char string index) #\:)))
315       (when (char= (char string index) #\\)
316         (incf index))
317       (incf index))
318     (cond
319       ;; No package prefix
320       ((= index size)
321        (setq name string)
322        (setq package *package*)
323        (setq internalp t))
324       (t
325        ;; Package prefix
326        (if (zerop index)
327            (setq package "KEYWORD")
328            (setq package (string-upcase-noescaped (subseq string 0 index))))
329        (incf index)
330        (when (char= (char string index) #\:)
331          (setq internalp t)
332          (incf index))
333        (setq name (subseq string index))))
334     ;; Canonalize symbol name and package
335     (setq name (if (equal package "JS")
336                    (setq name (unescape-token name))
337                    (setq name (string-upcase-noescaped name))))
338     (setq package (find-package package))
339     (if (or internalp
340             (eq package (find-package "KEYWORD"))
341             (eq package (find-package "JS")))
342         (intern name package)
343         (multiple-value-bind (symbol external)
344             (find-symbol name package)
345           (if (eq external :external)
346               symbol
347               (error "The symbol `~S' is not external in the package ~S." name package))))))
348
349 (defun read-integer (string)
350   (let ((sign 1)
351         (number nil)
352         (size (length string)))
353     (dotimes (i size)
354       (let ((elt (char string i)))
355         (cond
356           ((digit-char-p elt)
357            (setq number (+ (* (or number 0) 10) (digit-char-p elt))))
358           ((zerop i)
359            (case elt
360              (#\+ nil)
361              (#\- (setq sign -1))
362              (t (return-from read-integer))))
363           ((and (= i (1- size)) (char= elt #\.)) nil)
364           (t (return-from read-integer)))))
365     (and number (* sign number))))
366
367 (defun read-float (string)
368   (block nil
369     (let ((sign 1)
370           (integer-part nil)
371           (fractional-part nil)
372           (number 0)
373           (divisor 1)
374           (exponent-sign 1)
375           (exponent 0)
376           (size (length string))
377           (index 0))
378       (when (zerop size) (return))
379       ;; Optional sign
380       (case (char string index)
381         (#\+ (incf index))
382         (#\- (setq sign -1)
383              (incf index)))
384       (unless (< index size) (return))
385       ;; Optional integer part
386       (awhen (digit-char-p (char string index))
387         (setq integer-part t)
388         (while (and (< index size)
389                     (setq it (digit-char-p (char string index))))
390           (setq number (+ (* number 10) it))
391           (incf index)))
392       (unless (< index size) (return))
393       ;; Decimal point is mandatory if there's no integer part
394       (unless (or integer-part (char= #\. (char string index))) (return))
395       ;; Optional fractional part
396       (when (char= #\. (char string index))
397         (incf index)
398         (unless (< index size) (return))
399         (awhen (digit-char-p (char string index))
400           (setq fractional-part t)
401           (while (and (< index size)
402                       (setq it (digit-char-p (char string index))))
403             (setq number (+ (* number 10) it))
404             (setq divisor (* divisor 10))
405             (incf index))))
406       ;; Either left or right part of the dot must be present
407       (unless (or integer-part fractional-part) (return))
408       ;; Exponent is mandatory if there is no fractional part
409       (when (and (= index size) (not fractional-part)) (return))
410       ;; Optional exponent part
411       (when (< index size)
412         ;; Exponent-marker
413         (unless (find (char-upcase (char string index)) "ESFDL")
414           (return))
415         (incf index)
416         (unless (< index size) (return))
417         ;; Optional exponent sign
418         (case (char string index)
419           (#\+ (incf index))
420           (#\- (setq exponent-sign -1)
421                (incf index)))
422         (unless (< index size) (return))
423         ;; Exponent digits
424         (let ((value (digit-char-p (char string index))))
425           (unless value (return))
426           (while (and (< index size)
427                       (setq value (digit-char-p (char string index))))
428             (setq exponent (+ (* exponent 10) value))
429             (incf index))))
430       (unless (= index size) (return))
431       ;; Everything went ok, we have a float
432       ;; XXX: Use FLOAT when implemented.
433       (/ (* sign (expt 10.0 (* exponent-sign exponent)) number) divisor 1.0))))
434
435 (defun !parse-integer (string junk-allow)
436   (block nil
437     (let ((value 0)
438           (index 0)
439           (size (length string))
440           (sign 1))
441       ;; Leading whitespace
442       (while (and (< index size)
443                   (whitespacep (char string index)))
444         (incf index))
445       (unless (< index size) (return (values nil 0)))
446       ;; Optional sign
447       (case (char string 0)
448         (#\+ (incf index))
449         (#\- (setq sign -1)
450              (incf index)))
451       ;; First digit
452       (unless (and (< index size)
453                    (setq value (digit-char-p (char string index))))
454         (return (values nil index)))
455       (incf index)
456       ;; Other digits
457       (while (< index size)
458         (let ((digit (digit-char-p (char string index))))
459           (unless digit (return))
460           (setq value (+ (* value 10) digit))
461           (incf index)))
462       ;; Trailing whitespace
463       (do ((i index (1+ i)))
464           ((or (= i size) (not (whitespacep (char string i))))
465            (and (= i size) (setq index i))))
466       (if (or junk-allow
467               (= index size))
468           (values (* sign value) index)
469           (values nil index)))))
470
471 #+jscl
472 (defun parse-integer (string &key junk-allowed)
473   (multiple-value-bind (num index)
474       (!parse-integer string junk-allowed)
475     (if num
476         (values num index)
477         (error "Junk detected."))))
478
479
480 (defun interpret-token (string)
481   (or (read-integer string)
482       (read-float string)
483       (read-symbol string)))
484
485 (defun ls-read (stream &optional (eof-error-p t) eof-value recursive-p)
486   (let ((save-labelled-objects *labelled-objects*)
487         (save-fixup-locations *fixup-locations*))
488     (unless recursive-p
489       (setf *fixup-locations* nil)
490       (setf *labelled-objects* (new-labelled-objects-table)))
491     (prog1
492         (progn
493           (skip-whitespaces-and-comments stream)
494           (let ((ch (%peek-char stream)))
495             (cond
496               ((or (null ch) (char= ch #\)))
497                (if eof-error-p
498                    (error "End of file")
499                    eof-value))
500               ((char= ch #\()
501                (%read-char stream)
502                (%read-list stream eof-error-p eof-value))
503               ((char= ch #\')
504                (%read-char stream)
505                (list 'quote (ls-read stream eof-error-p eof-value t)))
506               ((char= ch #\`)
507                (%read-char stream)
508                (list 'backquote (ls-read stream eof-error-p eof-value t)))
509               ((char= ch #\")
510                (%read-char stream)
511                (read-string stream))
512               ((char= ch #\,)
513                (%read-char stream)
514                (if (eql (%peek-char stream) #\@)
515                    (progn (%read-char stream) (list 'unquote-splicing
516                                                     (ls-read stream eof-error-p eof-value t)))
517                    (list 'unquote (ls-read stream eof-error-p eof-value t))))
518               ((char= ch #\#)
519                (read-sharp stream eof-error-p eof-value))
520               (t
521                (let ((string (read-escaped-until stream #'terminalp)))
522                  (interpret-token string))))))
523       (unless recursive-p
524         (fixup-backrefs)
525         (setf *labelled-objects* save-labelled-objects)
526         (setf *fixup-locations* save-fixup-locations)))))
527
528 (defun ls-read-from-string (string &optional (eof-error-p t) eof-value)
529   (ls-read (make-string-stream string) eof-error-p eof-value))
530
531 #+jscl
532 (defun read-from-string (string &optional (eof-errorp t) eof-value)
533   (ls-read-from-string string eof-errorp eof-value))