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