Some refactoring
[jscl.git] / src / print.lisp
1 ;;; print.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 (/debug "loading print.lisp!")
20
21 ;;; Printer
22
23 (defun lisp-escape-string (string)
24   (let ((output "")
25         (index 0)
26         (size (length string)))
27     (while (< index size)
28       (let ((ch (char string index)))
29         (when (or (char= ch #\") (char= ch #\\))
30           (setq output (concat output "\\")))
31         (when (or (char= ch #\newline))
32           (setq output (concat output "\\"))
33           (setq ch #\n))
34         (setq output (concat output (string ch))))
35       (incf index))
36     (concat "\"" output "\"")))
37
38 ;;; Return T if the string S contains characters which need to be
39 ;;; escaped to print the symbol name, NIL otherwise.
40 (defun escape-symbol-name-p (s)
41   (let ((dots-only t))
42     (dotimes (i (length s))
43       (let ((ch (char s i)))
44         (setf dots-only (and dots-only (char= ch #\.)))
45         (when (or (terminalp ch)
46                   (char= ch #\:)
47                   (char= ch #\\)
48                   (char= ch #\|))
49           (return-from escape-symbol-name-p t))))
50     dots-only))
51
52 ;;; Return T if the specified string can be read as a number
53 ;;; In case such a string is the name of a symbol then escaping
54 ;;; is required when printing to ensure correct reading.
55 (defun potential-number-p (string)
56   ;; The four rules for being a potential number are described in
57   ;; 2.3.1.1 Potential Numbers as Token
58   ;;
59   ;; First Rule
60   (dotimes (i (length string))
61     (let ((char (char string i)))
62       (cond
63         ;; Digits TODO: DIGIT-CHAR-P should work with the current
64         ;; radix here. If the radix is not decimal, then we have to
65         ;; make sure there is not a decimal-point in the string.
66         ((digit-char-p char))
67         ;; Signs, ratios, decimal point and extension mark
68         ((find char "+-/._^"))
69         ;; Number marker
70         ((alpha-char-p char)
71          (when (and (< i (1- (length string)))
72                     (alpha-char-p (char string (1+ i))))
73            ;; fail: adjacent letters are not number marker, or
74            ;; there is a decimal point in the string.
75            (return-from potential-number-p)))
76         (t
77          ;; fail: there is a non-allowed character
78          (return-from potential-number-p)))))
79   (and
80    ;; Second Rule. In particular string is not empty.
81    (find-if #'digit-char-p string)
82    ;; Third rule
83    (let ((first (char string 0)))
84      (and (not (char= first #\:))
85           (or (digit-char-p first)
86               (find first "+-._^"))))
87    ;; Fourth rule
88    (not (find (char string (1- (length string))) "+-)"))))
89
90 #+nil
91 (mapcar #'potential-number-p
92         '("1b5000" "777777q" "1.7J" "-3/4+6.7J" "12/25/83" "27^19"
93           "3^4/5" "6//7" "3.1.2.6" "^-43^" "3.141_592_653_589_793_238_4"
94           "-3.7+2.6i-6.17j+19.6k"))
95
96 #+nil
97 (mapcar #'potential-number-p '("/" "/5" "+" "1+" "1-" "foo+" "ab.cd" "_" "^" "^/-"))
98
99 (defun escape-token-p (string)
100   (or (potential-number-p string)
101       (escape-symbol-name-p string)))
102
103 ;;; Returns the token in a form that can be used for reading it back.
104 (defun escape-token (s)
105   (if (escape-token-p s)
106       (let ((result "|"))
107         (dotimes (i (length s))
108           (let ((ch (char s i)))
109             (when (or (char= ch #\|)
110                       (char= ch #\\))
111               (setf result (concat result "\\")))
112             (setf result (concat result (string ch)))))
113         (concat result "|"))
114       s))
115
116 (defvar *print-escape* t)
117 (defvar *print-circle* nil)
118
119 ;;; FIXME: Please, rewrite this in a more organized way.
120 (defun write-to-string (form &optional known-objects object-ids)
121   (when (and (not known-objects) *print-circle*)
122     ;; To support *print-circle* some objects must be tracked for
123     ;; sharing: conses, arrays and apparently-uninterned symbols.
124     ;; These objects are placed in an array and a parallel array is
125     ;; used to mark if they're found multiple times by assining them
126     ;; an id starting from 1.
127     ;;
128     ;; After the tracking has been completed the printing phas can
129     ;; begin: if an object has an id > 0 then #<n>= is prefixed and
130     ;; the id is changed to negative. If an object has an id < 0 then
131     ;; #<-n># is printed instead of the object.
132     ;;
133     ;; The processing is O(n^2) with n = number of tracked
134     ;; objects. Hopefully it will become good enough when the new
135     ;; compiler is available.
136     (setf known-objects (make-array 100))
137     (setf object-ids (make-array 100))
138     (let ((n 0)
139           (sz 100)
140           (count 0))
141       (labels ((mark (x)
142                  (let ((i (position x known-objects)))
143                    (if (= i -1)
144                        (progn
145                          (when (= n sz)
146                            (setf sz (* 2 sz))
147                            ;; KLUDGE: storage vectors are an internal
148                            ;; object which the printer should not know
149                            ;; about. Use standard vector with fill
150                            ;; pointers instead.
151                            (resize-storage-vector known-objects sz)
152                            (resize-storage-vector object-ids sz))
153                          (aset known-objects (1- (incf n)) x)
154                          t)
155                        (unless (aref object-ids i)
156                          (aset object-ids i (incf count))
157                          nil))))
158                (visit (x)
159                  (cond
160                    ((and x (symbolp x) (null (symbol-package x)))
161                     (mark x))
162                    ((consp x)
163                     (when (mark x)
164                       (visit (car x))
165                       (visit (cdr x))))
166                    ((vectorp x)
167                     (when (mark x)
168                       (dotimes (i (length x))
169                         (visit (aref x i))))))))
170         (visit form))))
171   (let ((prefix ""))
172     (when (and *print-circle*
173                (or (consp form)
174                    (vectorp form)
175                    (and form (symbolp form) (null (symbol-package form)))))
176       (let* ((ix (position form known-objects))
177              (id (aref object-ids ix)))
178         (cond
179           ((and id (> id 0))
180            (setf prefix (format nil "#~S=" id))
181            (aset object-ids ix (- id)))
182           ((and id (< id 0))
183            (return-from write-to-string (format nil "#~S#" (- id)))))))
184     (concat prefix
185             (cond
186               ((null form) "NIL")
187               ((symbolp form)
188                (let ((name (symbol-name form))
189                      (package (symbol-package form)))
190                  ;; Check if the symbol is accesible from the current package. It
191                  ;; is true even if the symbol's home package is not the current
192                  ;; package, because it could be inherited.
193                  (if (eq form (find-symbol (symbol-name form)))
194                      (escape-token (symbol-name form))
195                      ;; Symbol is not accesible from *PACKAGE*, so let us prefix
196                      ;; the symbol with the optional package or uninterned mark.
197                      (concat (cond
198                                ((null package) "#")
199                                ((eq package (find-package "KEYWORD")) "")
200                                (t (escape-token (package-name package))))
201                              ":"
202                              (if (and package
203                                       (eq (second (multiple-value-list
204                                                       (find-symbol name package)))
205                                           :internal))
206                                  ":"
207                                  "")
208                              (escape-token name)))))
209               ((integerp form) (integer-to-string form))
210               ((floatp form) (float-to-string form))
211               ((characterp form)
212                (concat "#\\"
213                        (case form
214                          (#\newline "newline")
215                          (#\space "space")
216                          (otherwise (string form)))))
217               ((stringp form) (if *print-escape*
218                                   (lisp-escape-string form)
219                                   form))
220               ((functionp form)
221                (let ((name (oget form "fname")))
222                  (if name
223                      (concat "#<FUNCTION " name ">")
224                      (concat "#<FUNCTION>"))))
225               ((listp form)
226                (concat "("
227                        (join-trailing (mapcar (lambda (x)
228                                                 (write-to-string x known-objects object-ids))
229                                               (butlast form)) " ")
230                        (let ((last (last form)))
231                          (if (null (cdr last))
232                              (write-to-string (car last) known-objects object-ids)
233                              (concat (write-to-string (car last) known-objects object-ids)
234                                      " . "
235                                      (write-to-string (cdr last) known-objects object-ids))))
236                        ")"))
237               ((vectorp form)
238                (let ((result "#(")
239                      (sep ""))
240                  (dotimes (i (length form))
241                    (setf result (concat result sep
242                                         (write-to-string (aref form i)
243                                                          known-objects
244                                                          object-ids)))
245                    (setf sep " "))
246                  (concat result ")")))
247               ((packagep form)
248                (concat "#<PACKAGE " (package-name form) ">"))
249               (t "#<javascript object>")))))
250
251 (defun prin1-to-string (form)
252   (let ((*print-escape* t))
253     (write-to-string form)))
254
255 (defun princ-to-string (form)
256   (let ((*print-escape* nil))
257     (write-to-string form)))
258
259 (defun write-line (x)
260   (write-string x)
261   (write-string *newline*)
262   x)
263
264 (defun warn (string)
265   (write-string "WARNING: ")
266   (write-line string))
267
268 (defun print (x)
269   (write-line (prin1-to-string x))
270   x)
271
272 (defun format (destination fmt &rest args)
273   (let ((len (length fmt))
274         (i 0)
275         (res "")
276         (arguments args))
277     (while (< i len)
278       (let ((c (char fmt i)))
279         (if (char= c #\~)
280             (let ((next (char fmt (incf i))))
281               (cond
282                ((char= next #\~)
283                 (concatf res "~"))
284                ((char= next #\%)
285                 (concatf res *newline*))
286                ((char= next #\*)
287                 (pop arguments))
288                (t
289                 (concatf res (format-special next (car arguments)))
290                 (pop arguments))))
291             (setq res (concat res (string c))))
292         (incf i)))
293     (if destination
294         (progn
295           (write-string res)
296           nil)
297         res)))
298
299 (defun format-special (chr arg)
300   (case (char-upcase chr)
301     (#\S (prin1-to-string arg))
302     (#\A (princ-to-string arg))))