83f1af8e9cc163e8d256c9b8992e5c5bdb26fb35
[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 (defun make-string-stream (string)
26   (cons string 0))
27
28 (defun %peek-char (stream)
29   (and (< (cdr stream) (length (car stream)))
30        (char (car stream) (cdr stream))))
31
32 (defun %read-char (stream)
33   (and (< (cdr stream) (length (car stream)))
34        (prog1 (char (car stream) (cdr stream))
35          (rplacd stream (1+ (cdr stream))))))
36
37 (defun whitespacep (ch)
38   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
39
40 (defun skip-whitespaces (stream)
41   (let (ch)
42     (setq ch (%peek-char stream))
43     (while (and ch (whitespacep ch))
44       (%read-char stream)
45       (setq ch (%peek-char stream)))))
46
47 (defun terminalp (ch)
48   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
49
50 (defun read-until (stream func)
51   (let ((string "")
52         (ch))
53     (setq ch (%peek-char stream))
54     (while (and ch (not (funcall func ch)))
55       (setq string (concat string (string ch)))
56       (%read-char stream)
57       (setq ch (%peek-char stream)))
58     string))
59
60 (defun read-escaped-until (stream func)
61   (let ((string "")
62         (ch (%peek-char stream))
63         (multi-escape nil))
64     (while (and ch (or multi-escape (not (funcall func ch))))
65       (cond
66         ((char= ch #\|)
67          (if multi-escape
68              (setf multi-escape nil)
69              (setf multi-escape t)))
70         ((char= ch #\\)
71          (%read-char stream)
72          (setf ch (%peek-char stream))
73          (setf string (concat string "\\" (string ch))))
74         (t
75          (if multi-escape
76              (setf string (concat string "\\" (string ch)))
77              (setf string (concat string (string ch))))))
78       (%read-char stream)
79       (setf ch (%peek-char stream)))
80     string))
81
82 (defun skip-whitespaces-and-comments (stream)
83   (let (ch)
84     (skip-whitespaces stream)
85     (setq ch (%peek-char stream))
86     (while (and ch (char= ch #\;))
87       (read-until stream (lambda (x) (char= x #\newline)))
88       (skip-whitespaces stream)
89       (setq ch (%peek-char stream)))))
90
91 (defun discard-char (stream expected)
92   (let ((ch (%read-char stream)))
93     (when (null ch)
94       (error "End of file when character ~S was expected." expected))
95     (unless (char= ch expected)
96       (error "Character ~S was found but ~S was expected." ch expected))))
97
98 (defun %read-list (stream)
99   (skip-whitespaces-and-comments stream)
100   (let ((ch (%peek-char stream)))
101     (cond
102      ((null ch)
103       (error "Unspected EOF"))
104      ((char= ch #\))
105       (discard-char stream #\))
106       nil)
107      (t
108       (let* ((eof (gensym))
109              (next (ls-read stream nil eof)))
110         (skip-whitespaces-and-comments stream)
111         (cond
112          ((eq next eof)
113           (discard-char stream #\)))
114          (t
115           (cons next
116                 (if (char= (%peek-char stream) #\.)
117                     (progn
118                       (discard-char stream #\.)
119                       (if (terminalp (%peek-char stream))
120                           (prog1 (ls-read stream) ; Dotted pair notation
121                             (skip-whitespaces-and-comments stream)
122                             (let ((ch (%peek-char stream)))
123                               (if (or (null ch) (char= #\) ch))
124                                   (discard-char stream #\))
125                                   (error "Multiple objects following . in a list"))))
126                           (let ((token (concat "." (read-escaped-until stream #'terminalp))))
127                             (cons (interpret-token token)
128                                   (%read-list stream)))))
129                     (%read-list stream))))))))))
130
131 (defun read-string (stream)
132   (let ((string "")
133         (ch nil))
134     (setq ch (%read-char stream))
135     (while (not (eql ch #\"))
136       (when (null ch)
137         (error "Unexpected EOF"))
138       (when (eql ch #\\)
139         (setq ch (%read-char stream)))
140       (setq string (concat string (string ch)))
141       (setq ch (%read-char stream)))
142     string))
143
144 (defun read-sharp (stream &optional eof-error-p eof-value)
145   (%read-char stream)
146   (ecase (%read-char stream)
147     (#\'
148      (list 'function (ls-read stream)))
149     (#\( (list-to-vector (%read-list stream)))
150     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
151     (#\\
152      (let ((cname
153             (concat (string (%read-char stream))
154                     (read-until stream #'terminalp))))
155        (cond
156          ((string= cname "space") #\space)
157          ((string= cname "tab") #\tab)
158          ((string= cname "newline") #\newline)
159          (t (char cname 0)))))
160     (#\+
161      (let ((feature (let ((symbol (ls-read stream)))
162                       (unless (symbolp symbol)
163                         (error "Invalid feature ~S" symbol))
164                       (intern (string symbol) "KEYWORD"))))
165        (ecase feature
166          (:common-lisp
167           (ls-read stream)
168           (ls-read stream eof-error-p eof-value))
169          (:jscl
170           (ls-read stream eof-error-p eof-value)))))))
171
172 (defun unescape (x)
173   (let ((result ""))
174     (dotimes (i (length x))
175       (unless (char= (char x i) #\\)
176         (setq result (concat result (string (char x i))))))
177     result))
178
179 (defun string-upcase-noescaped (s)
180   (let ((result "")
181         (last-escape nil))
182     (dotimes (i (length s))
183       (let ((ch (char s i)))
184         (if last-escape
185            (progn
186               (setf last-escape nil)
187               (setf result (concat result (string ch))))
188             (if (char= ch #\\)
189                 (setf last-escape t)
190                 (setf result (concat result (string-upcase (string ch))))))))
191     result))
192
193 ;;; Parse a string of the form NAME, PACKAGE:NAME or
194 ;;; PACKAGE::NAME and return the name. If the string is of the
195 ;;; form 1) or 3), but the symbol does not exist, it will be created
196 ;;; and interned in that package.
197 (defun read-symbol (string)
198   (let ((size (length string))
199         package name internalp index)
200     (setq index 0)
201     (while (and (< index size)
202                 (not (char= (char string index) #\:)))
203       (when (char= (char string index) #\\)
204         (incf index))
205       (incf index))
206     (cond
207       ;; No package prefix
208       ((= index size)
209        (setq name string)
210        (setq package *package*)
211        (setq internalp t))
212       (t
213        ;; Package prefix
214        (if (zerop index)
215            (setq package "KEYWORD")
216            (setq package (string-upcase-noescaped (subseq string 0 index))))
217        (incf index)
218        (when (char= (char string index) #\:)
219          (setq internalp t)
220          (incf index))
221        (setq name (subseq string index))))
222     ;; Canonalize symbol name and package
223     (setq name (if (equal package "JS")
224                    (setq name (unescape name))
225                    (setq name (string-upcase-noescaped name))))
226     (setq package (find-package package))
227     (if (or internalp
228             (eq package (find-package "KEYWORD"))
229             (eq package (find-package "JS")))
230         (intern name package)
231         (multiple-value-bind (symbol external)
232             (find-symbol name package)
233           (if (eq external :external)
234               symbol
235               (error "The symbol `~S' is not external in the package ~S." name package))))))
236
237 (defun read-integer (string)
238   (let ((sign 1)
239         (number nil)
240         (size (length string)))
241     (dotimes (i size)
242       (let ((elt (char string i)))
243         (cond
244           ((digit-char-p elt)
245            (setq number (+ (* (or number 0) 10) (digit-char-p elt))))
246           ((zerop i)
247            (case elt
248              (#\+ nil)
249              (#\- (setq sign -1))
250              (t (return-from read-integer))))
251           ((and (= i (1- size)) (char= elt #\.)) nil)
252           (t (return-from read-integer)))))
253     (and number (* sign number))))
254
255 (defun read-float (string)
256   (block nil
257     (let ((sign 1)
258           (integer-part nil)
259           (fractional-part nil)
260           (number 0)
261           (divisor 1)
262           (exponent-sign 1)
263           (exponent 0)
264           (size (length string))
265           (index 0))
266       (when (zerop size) (return))
267       ;; Optional sign
268       (case (char string index)
269         (#\+ (incf index))
270         (#\- (setq sign -1)
271              (incf index)))
272       (unless (< index size) (return))
273       ;; Optional integer part
274       (awhen (digit-char-p (char string index))
275         (setq integer-part t)
276         (while (and (< index size)
277                     (setq it (digit-char-p (char string index))))
278           (setq number (+ (* number 10) it))
279           (incf index)))
280       (unless (< index size) (return))
281       ;; Decimal point is mandatory if there's no integer part
282       (unless (or integer-part (char= #\. (char string index))) (return))
283       ;; Optional fractional part
284       (when (char= #\. (char string index))
285         (incf index)
286         (unless (< index size) (return))
287         (awhen (digit-char-p (char string index))
288           (setq fractional-part t)
289           (while (and (< index size)
290                       (setq it (digit-char-p (char string index))))
291             (setq number (+ (* number 10) it))
292             (setq divisor (* divisor 10))
293             (incf index))))
294       ;; Either left or right part of the dot must be present
295       (unless (or integer-part fractional-part) (return))
296       ;; Exponent is mandatory if there is no fractional part
297       (when (and (= index size) (not fractional-part)) (return))
298       ;; Optional exponent part
299       (when (< index size)
300         ;; Exponent-marker
301         (unless (member (string-upcase (string (char string index)))
302                         '("E" "S" "F" "D" "L"))
303           (return))
304         (incf index)
305         (unless (< index size) (return))
306         ;; Optional exponent sign
307         (case (char string index)
308           (#\+ (incf index))
309           (#\- (setq exponent-sign -1)
310                (incf index)))
311         (unless (< index size) (return))
312         ;; Exponent digits
313         (let ((value (digit-char-p (char string index))))
314           (unless value (return))
315           (while (and (< index size)
316                       (setq value (digit-char-p (char string index))))
317             (setq exponent (+ (* exponent 10) value))
318             (incf index))))
319       (unless (= index size) (return))
320       ;; Everything went ok, we have a float
321       ;; XXX: Use FLOAT when implemented.
322       (/ (* sign (expt 10.0 (* exponent-sign exponent)) number) divisor))))
323
324 (defun !parse-integer (string junk-allow)
325   (block nil
326     (let ((value 0)
327           (index 0)
328           (size (length string))
329           (sign 1))
330       ;; Leading whitespace
331       (while (and (< index size)
332                   (whitespacep (char string index)))
333         (incf index))
334       (unless (< index size) (return (values nil 0)))
335       ;; Optional sign
336       (case (char string 0)
337         (#\+ (incf index))
338         (#\- (setq sign -1)
339              (incf index)))
340       ;; First digit
341       (unless (and (< index size)
342                    (setq value (digit-char-p (char string index))))
343         (return (values nil index)))
344       (incf index)
345       ;; Other digits
346       (while (< index size)
347         (let ((digit (digit-char-p (char string index))))
348           (unless digit (return))
349           (setq value (+ (* value 10) digit))
350           (incf index)))
351       ;; Trailing whitespace
352       (do ((i index (1+ i)))
353           ((or (= i size) (not (whitespacep (char string i))))
354            (and (= i size) (setq index i))))
355       (if (or junk-allow
356               (= index size))
357           (values (* sign value) index)
358           (values nil index)))))
359
360 #+jscl
361 (defun parse-integer (string &key junk-allowed)
362   (multiple-value-bind (num index)
363       (!parse-integer string junk-allowed)
364     (if num
365         (values num index)
366         (error "Junk detected."))))
367
368
369 (defun interpret-token (string)
370   (or (read-integer string)
371       (read-float string)
372       (read-symbol string)))
373
374 (defun ls-read (stream  &optional (eof-error-p t) eof-value)
375   (skip-whitespaces-and-comments stream)
376   (let ((ch (%peek-char stream)))
377     (cond
378       ((or (null ch) (char= ch #\)))
379        (if eof-error-p
380            (error "End of file")
381            eof-value))
382       ((char= ch #\()
383        (%read-char stream)
384        (%read-list stream))
385       ((char= ch #\')
386        (%read-char stream)
387        (list 'quote (ls-read stream)))
388       ((char= ch #\`)
389        (%read-char stream)
390        (list 'backquote (ls-read stream)))
391       ((char= ch #\")
392        (%read-char stream)
393        (read-string stream))
394       ((char= ch #\,)
395        (%read-char stream)
396        (if (eql (%peek-char stream) #\@)
397            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
398            (list 'unquote (ls-read stream))))
399       ((char= ch #\#)
400        (read-sharp stream))
401       (t
402        (let ((string (read-escaped-until stream #'terminalp)))
403          (interpret-token string))))))
404
405 (defun ls-read-from-string (string &optional (eof-error-p t) eof-value)
406   (ls-read (make-string-stream string) eof-error-p eof-value))
407
408 #+jscl
409 (defun read-from-string (string &optional (eof-errorp t) eof-value)
410   (ls-read-from-string string eof-errorp eof-value))