c3cde1b150b7f1255d07576ead558b3a32270c10
[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       ((char= ch #\+)
241        (let ((feature (let ((symbol (ls-read stream eof-error-p eof-value t)))
242                         (unless (symbolp symbol)
243                           (error "Invalid feature ~S" symbol))
244                         (intern (string symbol) "KEYWORD"))))
245          (ecase feature
246            (:common-lisp
247               (ls-read stream)
248               (ls-read stream eof-error-p eof-value t))
249            (:jscl
250               (ls-read stream eof-error-p eof-value t))
251            (:nil
252               (ls-read stream)
253               (ls-read stream eof-error-p eof-value t)))))
254       ((and ch (digit-char-p ch))
255        (let ((id (digit-char-p ch)))
256          (while (and (%peek-char stream)
257                      (digit-char-p (%peek-char stream)))
258            (setf id (+ (* id 10) (digit-char-p (%read-char stream)))))
259          (ecase (%peek-char stream)
260            (#\=
261               (%read-char stream)
262               (if (find-labelled-object id)
263                   (error "Duplicated label #~S=" id)
264                   (progn
265                     (add-labelled-object id *future-value*)
266                     (let ((obj (ls-read stream eof-error-p eof-value t)))
267                       ;; FIXME: somehow the more natural
268                       ;;    (setf (cdr (find-labelled-object id)) obj)
269                       ;; doesn't work
270                       (rplacd (find-labelled-object id) obj)
271                       obj))))
272            (#\#
273               (%read-char stream)
274               (let ((cell (find-labelled-object id)))
275                 (if cell
276                     (if (eq (cdr cell) *future-value*)
277                         (progn
278                           (push (cons (funcall *make-fixup-function*)
279                                       id)
280                                 *fixup-locations*)
281                           *fixup-value*)
282                         (cdr cell))
283                     (error "Invalid labelled object #~S#" id)))))))
284       (t
285        (error "Invalid dispatch character after #")))))
286
287 (defun unescape-token (x)
288   (let ((result ""))
289     (dotimes (i (length x))
290       (unless (char= (char x i) #\\)
291         (setq result (concat result (string (char x i))))))
292     result))
293
294 (defun string-upcase-noescaped (s)
295   (let ((result "")
296         (last-escape nil))
297     (dotimes (i (length s))
298       (let ((ch (char s i)))
299         (if last-escape
300            (progn
301               (setf last-escape nil)
302               (setf result (concat result (string ch))))
303             (if (char= ch #\\)
304                 (setf last-escape t)
305                 (setf result (concat result (string-upcase (string ch))))))))
306     result))
307
308 ;;; Parse a string of the form NAME, PACKAGE:NAME or
309 ;;; PACKAGE::NAME and return the name. If the string is of the
310 ;;; form 1) or 3), but the symbol does not exist, it will be created
311 ;;; and interned in that package.
312 (defun read-symbol (string)
313   (let ((size (length string))
314         package name internalp index)
315     (setq index 0)
316     (while (and (< index size)
317                 (not (char= (char string index) #\:)))
318       (when (char= (char string index) #\\)
319         (incf index))
320       (incf index))
321     (cond
322       ;; No package prefix
323       ((= index size)
324        (setq name string)
325        (setq package *package*)
326        (setq internalp t))
327       (t
328        ;; Package prefix
329        (if (zerop index)
330            (setq package "KEYWORD")
331            (setq package (string-upcase-noescaped (subseq string 0 index))))
332        (incf index)
333        (when (char= (char string index) #\:)
334          (setq internalp t)
335          (incf index))
336        (setq name (subseq string index))))
337     ;; Canonalize symbol name and package
338     (setq name (if (equal package "JS")
339                    (setq name (unescape-token name))
340                    (setq name (string-upcase-noescaped name))))
341     (setq package (find-package package))
342     (if (or internalp
343             (eq package (find-package "KEYWORD"))
344             (eq package (find-package "JS")))
345         (intern name package)
346         (multiple-value-bind (symbol external)
347             (find-symbol name package)
348           (if (eq external :external)
349               symbol
350               (error "The symbol `~S' is not external in the package ~S." name package))))))
351
352 (defun read-integer (string)
353   (let ((sign 1)
354         (number nil)
355         (size (length string)))
356     (dotimes (i size)
357       (let ((elt (char string i)))
358         (cond
359           ((digit-char-p elt)
360            (setq number (+ (* (or number 0) 10) (digit-char-p elt))))
361           ((zerop i)
362            (case elt
363              (#\+ nil)
364              (#\- (setq sign -1))
365              (t (return-from read-integer))))
366           ((and (= i (1- size)) (char= elt #\.)) nil)
367           (t (return-from read-integer)))))
368     (and number (* sign number))))
369
370 (defun read-float (string)
371   (block nil
372     (let ((sign 1)
373           (integer-part nil)
374           (fractional-part nil)
375           (number 0)
376           (divisor 1)
377           (exponent-sign 1)
378           (exponent 0)
379           (size (length string))
380           (index 0))
381       (when (zerop size) (return))
382       ;; Optional sign
383       (case (char string index)
384         (#\+ (incf index))
385         (#\- (setq sign -1)
386              (incf index)))
387       (unless (< index size) (return))
388       ;; Optional integer part
389       (awhen (digit-char-p (char string index))
390         (setq integer-part t)
391         (while (and (< index size)
392                     (setq it (digit-char-p (char string index))))
393           (setq number (+ (* number 10) it))
394           (incf index)))
395       (unless (< index size) (return))
396       ;; Decimal point is mandatory if there's no integer part
397       (unless (or integer-part (char= #\. (char string index))) (return))
398       ;; Optional fractional part
399       (when (char= #\. (char string index))
400         (incf index)
401         (unless (< index size) (return))
402         (awhen (digit-char-p (char string index))
403           (setq fractional-part t)
404           (while (and (< index size)
405                       (setq it (digit-char-p (char string index))))
406             (setq number (+ (* number 10) it))
407             (setq divisor (* divisor 10))
408             (incf index))))
409       ;; Either left or right part of the dot must be present
410       (unless (or integer-part fractional-part) (return))
411       ;; Exponent is mandatory if there is no fractional part
412       (when (and (= index size) (not fractional-part)) (return))
413       ;; Optional exponent part
414       (when (< index size)
415         ;; Exponent-marker
416         (unless (find (char-upcase (char string index)) "ESFDL")
417           (return))
418         (incf index)
419         (unless (< index size) (return))
420         ;; Optional exponent sign
421         (case (char string index)
422           (#\+ (incf index))
423           (#\- (setq exponent-sign -1)
424                (incf index)))
425         (unless (< index size) (return))
426         ;; Exponent digits
427         (let ((value (digit-char-p (char string index))))
428           (unless value (return))
429           (while (and (< index size)
430                       (setq value (digit-char-p (char string index))))
431             (setq exponent (+ (* exponent 10) value))
432             (incf index))))
433       (unless (= index size) (return))
434       ;; Everything went ok, we have a float
435       ;; XXX: Use FLOAT when implemented.
436       (/ (* sign (expt 10.0 (* exponent-sign exponent)) number) divisor 1.0))))
437
438 (defun !parse-integer (string junk-allow)
439   (block nil
440     (let ((value 0)
441           (index 0)
442           (size (length string))
443           (sign 1))
444       ;; Leading whitespace
445       (while (and (< index size)
446                   (whitespacep (char string index)))
447         (incf index))
448       (unless (< index size) (return (values nil 0)))
449       ;; Optional sign
450       (case (char string 0)
451         (#\+ (incf index))
452         (#\- (setq sign -1)
453              (incf index)))
454       ;; First digit
455       (unless (and (< index size)
456                    (setq value (digit-char-p (char string index))))
457         (return (values nil index)))
458       (incf index)
459       ;; Other digits
460       (while (< index size)
461         (let ((digit (digit-char-p (char string index))))
462           (unless digit (return))
463           (setq value (+ (* value 10) digit))
464           (incf index)))
465       ;; Trailing whitespace
466       (do ((i index (1+ i)))
467           ((or (= i size) (not (whitespacep (char string i))))
468            (and (= i size) (setq index i))))
469       (if (or junk-allow
470               (= index size))
471           (values (* sign value) index)
472           (values nil index)))))
473
474 #+jscl
475 (defun parse-integer (string &key junk-allowed)
476   (multiple-value-bind (num index)
477       (!parse-integer string junk-allowed)
478     (if num
479         (values num index)
480         (error "Junk detected."))))
481
482
483 (defun interpret-token (string)
484   (or (read-integer string)
485       (read-float string)
486       (read-symbol string)))
487
488 (defun ls-read (stream &optional (eof-error-p t) eof-value recursive-p)
489   (let ((save-labelled-objects *labelled-objects*)
490         (save-fixup-locations *fixup-locations*))
491     (unless recursive-p
492       (setf *fixup-locations* nil)
493       (setf *labelled-objects* (new-labelled-objects-table)))
494     (prog1
495         (progn
496           (skip-whitespaces-and-comments stream)
497           (let ((ch (%peek-char stream)))
498             (cond
499               ((or (null ch) (char= ch #\)))
500                (if eof-error-p
501                    (error "End of file")
502                    eof-value))
503               ((char= ch #\()
504                (%read-char stream)
505                (%read-list stream eof-error-p eof-value))
506               ((char= ch #\')
507                (%read-char stream)
508                (list 'quote (ls-read stream eof-error-p eof-value t)))
509               ((char= ch #\`)
510                (%read-char stream)
511                (list 'backquote (ls-read stream eof-error-p eof-value t)))
512               ((char= ch #\")
513                (%read-char stream)
514                (read-string stream))
515               ((char= ch #\,)
516                (%read-char stream)
517                (if (eql (%peek-char stream) #\@)
518                    (progn (%read-char stream) (list 'unquote-splicing
519                                                     (ls-read stream eof-error-p eof-value t)))
520                    (list 'unquote (ls-read stream eof-error-p eof-value t))))
521               ((char= ch #\#)
522                (read-sharp stream eof-error-p eof-value))
523               (t
524                (let ((string (read-escaped-until stream #'terminalp)))
525                  (interpret-token string))))))
526       (unless recursive-p
527         (fixup-backrefs)
528         (setf *labelled-objects* save-labelled-objects)
529         (setf *fixup-locations* save-fixup-locations)))))
530
531 (defun ls-read-from-string (string &optional (eof-error-p t) eof-value)
532   (ls-read (make-string-stream string) eof-error-p eof-value))
533
534 #+jscl
535 (defun read-from-string (string &optional (eof-errorp t) eof-value)
536   (ls-read-from-string string eof-errorp eof-value))