1 ;;; compiler-codege.lisp --- Naive Javascript unparser
3 ;; copyright (C) 2013 David Vazquez
5 ;; JSCL is free software: you can redistribute it and/or
6 ;; modify it under the terms of the GNU General Public License as
7 ;; published by the Free Software Foundation, either version 3 of the
8 ;; License, or (at your option) any later version.
10 ;; JSCL is distributed in the hope that it will be useful, but
11 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;; General Public License for more details.
15 ;; You should have received a copy of the GNU General Public License
16 ;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
18 ;;; This code generator takes as input a S-expression representation
19 ;;; of the Javascript AST and generates Javascript code without
20 ;;; redundant syntax constructions like extra parenthesis.
22 ;;; It is intended to be used with the new compiler. However, it is
23 ;;; quite independent so it has been integrated early in JSCL.
25 (/debug "loading compiler-codegen.lisp!")
27 (defvar *js-macros* nil)
28 (defmacro define-js-macro (name lambda-list &body body)
29 (let ((form (gensym)))
33 (destructuring-bind ,lambda-list ,form
37 (defun js-macroexpand (js)
38 (if (and (consp js) (assoc (car js) *js-macros*))
39 (let ((expander (cdr (assoc (car js) *js-macros*))))
40 (multiple-value-bind (expansion stop-expand-p)
41 (funcall expander (cdr js))
44 (js-macroexpand expansion))))
48 (defconstant no-comma 12)
50 (defvar *js-output* t)
52 (defvar *js-pretty-print* t)
54 ;;; Two seperate functions are needed for escaping strings:
55 ;;; One for producing JavaScript string literals (which are singly or
57 ;;; And one for producing Lisp strings (which are only doubly quoted)
59 ;;; The same function would suffice for both, but for javascript string
60 ;;; literals it is neater to use either depending on the context, e.g:
63 ;;; which avoids having to escape quotes where possible
64 (defun js-escape-string (string)
66 (size (length string))
67 (seen-single-quote nil)
68 (seen-double-quote nil))
69 (flet ((%js-escape-string (string escape-single-quote-p)
73 (let ((ch (char string index)))
75 (setq output (concat output "\\")))
76 (when (and escape-single-quote-p (char= ch #\'))
77 (setq output (concat output "\\")))
78 (when (char= ch #\newline)
79 (setq output (concat output "\\"))
81 (setq output (concat output (string ch))))
84 ;; First, scan the string for single/double quotes
86 (let ((ch (char string index)))
88 (setq seen-single-quote t))
90 (setq seen-double-quote t)))
92 ;; Then pick the appropriate way to escape the quotes
94 ((not seen-single-quote)
95 (concat "'" (%js-escape-string string nil) "'"))
96 ((not seen-double-quote)
97 (concat "\"" (%js-escape-string string nil) "\""))
98 (t (concat "'" (%js-escape-string string t) "'"))))))
101 (defun js-format (fmt &rest args)
102 (apply #'format *js-output* fmt args))
104 (defun valid-js-identifier (string-designator)
105 (let ((string (typecase string-designator
106 (symbol (symbol-name string-designator))
107 (string string-designator)
109 (return-from valid-js-identifier (values nil nil))))))
110 (flet ((constitutentp (ch)
111 (or (alphanumericp ch) (member ch '(#\$ #\_)))))
112 (if (and (every #'constitutentp string)
113 (if (plusp (length string))
114 (not (digit-char-p (char string 0)))
116 (values (format nil "~a" string) t)
119 (defun js-identifier (string-designator)
120 (multiple-value-bind (string valid)
121 (valid-js-identifier string-designator)
123 (error "~S is not a valid Javascript identifier." string))
124 (js-format "~a" string)))
126 (defun js-primary-expr (form)
130 (js-format "~a" form)
131 (js-expr `(- ,(abs form)))))
133 (js-format "~a" (js-escape-string form)))
136 (true (js-format "true"))
137 (false (js-format "false"))
138 (null (js-format "null"))
139 (this (js-format "this"))
140 (undefined (js-format "undefined"))
142 (js-identifier form))))
144 (error "Unknown Javascript syntax ~S." form))))
146 (defun js-vector-initializer (vector)
147 (let ((size (length vector)))
149 (dotimes (i (1- size))
150 (let ((elt (aref vector i)))
151 (unless (eq elt 'null)
152 (js-expr elt no-comma))
155 (js-expr (aref vector (1- size)) no-comma))
158 (defun js-object-initializer (plist)
160 (do* ((tail plist (cddr tail)))
162 (let ((key (car tail))
164 (multiple-value-bind (identifier identifier-p) (valid-js-identifier key)
165 (declare (ignore identifier))
168 (js-expr (string key) no-comma)))
170 (js-expr value no-comma)
171 (unless (null (cddr tail))
175 (defun js-function (arguments &rest body)
176 (js-format "function(")
178 (js-identifier (car arguments))
179 (dolist (arg (cdr arguments))
181 (js-identifier arg)))
183 (js-stmt `(group ,@body) t))
185 (defun check-lvalue (x)
186 (unless (or (symbolp x)
187 (nth-value 1 (valid-js-identifier x))
189 (member (car x) '(get = property))))
190 (error "Bad Javascript lvalue ~S" x)))
192 ;;; Process the Javascript AST to reduce some syntax sugar.
193 (defun js-expand-expr (form)
197 (case (length (cdr form))
198 (1 `(unary+ ,(cadr form)))
199 (t (reduce (lambda (x y) `(+ ,x ,y)) (cdr form)))))
201 (case (length (cdr form))
202 (1 `(unary- ,(cadr form)))
203 (t (reduce (lambda (x y) `(- ,x ,y)) (cdr form)))))
205 (reduce (lambda (x y) `(,(car form) ,x ,y)) (cdr form)))
207 (reduce (lambda (x y) `(comma ,x ,y)) (cdr form) :from-end t))
209 (js-macroexpand form)))
212 (defun js-operator-expression (op args precedence associativity operand-order)
213 (let ((op1 (car args))
218 (js-expr (car args) 0)
220 (js-expr (cadr args) no-comma)
223 (multiple-value-bind (accessor accessorp)
224 (valid-js-identifier (cadr args))
226 (error "Invalid accessor ~S" (cadr args)))
227 (js-expr (car args) 0)
229 (js-identifier accessor)))
232 (js-expr (car args) 1)
235 (js-expr (cadr args) no-comma)
236 (dolist (operand (cddr args))
238 (js-expr operand no-comma)))
242 (js-object-initializer args))
243 ;; Function expressions
246 (apply #'js-function args)
249 (labels ((low-precedence-p (op-precedence)
251 ((> op-precedence precedence))
252 ((< op-precedence precedence) nil)
253 (t (not (eq operand-order associativity)))))
255 (%unary-op (operator string operator-precedence operator-associativity post lvalue)
256 (when (eq op operator)
257 (when lvalue (check-lvalue op1))
258 (when (low-precedence-p operator-precedence) (js-format "("))
261 (js-expr op1 operator-precedence operator-associativity 'left)
262 (js-format "~a" string))
264 (js-format "~a" string)
265 (js-expr op1 operator-precedence operator-associativity 'right)))
266 (when (low-precedence-p operator-precedence) (js-format ")"))
267 (return-from js-operator-expression)))
269 (%binary-op (operator string operator-precedence operator-associativity lvalue)
270 (when (eq op operator)
271 (when lvalue (check-lvalue op1))
272 (when (low-precedence-p operator-precedence) (js-format "("))
273 (js-expr op1 operator-precedence operator-associativity 'left)
274 (js-format "~a" string)
275 (js-expr op2 operator-precedence operator-associativity 'right)
276 (when (low-precedence-p operator-precedence) (js-format ")"))
277 (return-from js-operator-expression))))
279 (macrolet ((unary-op (operator string precedence associativity &key post lvalue)
280 `(%unary-op ',operator ',string ',precedence ',associativity ',post ',lvalue))
281 (binary-op (operator string precedence associativity &key lvalue)
282 `(%binary-op ',operator ',string ',precedence ',associativity ',lvalue)))
284 (unary-op pre++ "++" 2 right :lvalue t)
285 (unary-op pre-- "--" 2 right :lvalue t)
286 (unary-op post++ "++" 2 right :lvalue t :post t)
287 (unary-op post-- "--" 2 right :lvalue t :post t)
288 (unary-op not "!" 2 right)
289 (unary-op bit-not "~" 2 right)
290 ;; Note that the leading space is necessary because it
291 ;; could break with post++, for example. TODO: Avoid
292 ;; leading space when it's possible.
293 (unary-op unary+ " +" 2 right)
294 (unary-op unary- " -" 2 right)
295 (unary-op delete "delete " 2 right)
296 (unary-op void "void " 2 right)
297 (unary-op typeof "typeof " 2 right)
298 (unary-op new "new " 2 right)
300 (binary-op * "*" 3 left)
301 (binary-op / "/" 3 left)
302 (binary-op mod "%" 3 left)
303 (binary-op % "%" 3 left)
304 (binary-op + "+" 4 left)
305 (binary-op - "-" 5 left)
306 (binary-op << "<<" 5 left)
307 (binary-op >> "<<" 5 left)
308 (binary-op >>> ">>>" 5 left)
309 (binary-op <= "<=" 6 left)
310 (binary-op < "<" 6 left)
311 (binary-op > ">" 6 left)
312 (binary-op >= ">=" 6 left)
313 (binary-op instanceof " instanceof " 6 left)
314 (binary-op in " in " 6 left)
315 (binary-op == "==" 7 left)
316 (binary-op != "!=" 7 left)
317 (binary-op === "===" 7 left)
318 (binary-op !== "!==" 7 left)
319 (binary-op bit-and "&" 8 left)
320 (binary-op bit-xor "^" 9 left)
321 (binary-op bit-or "|" 10 left)
322 (binary-op and "&&" 11 left)
323 (binary-op or "||" 12 left)
324 (binary-op = "=" 13 right :lvalue t)
325 (binary-op += "+=" 13 right :lvalue t)
326 (binary-op incf "+=" 13 right :lvalue t)
327 (binary-op -= "-=" 13 right :lvalue t)
328 (binary-op decf "-=" 13 right :lvalue t)
329 (binary-op *= "*=" 13 right :lvalue t)
330 (binary-op /= "*=" 13 right :lvalue t)
331 (binary-op bit-xor= "^=" 13 right :lvalue t)
332 (binary-op bit-and= "&=" 13 right :lvalue t)
333 (binary-op bit-or= "|=" 13 right :lvalue t)
334 (binary-op <<= "<<=" 13 right :lvalue t)
335 (binary-op >>= ">>=" 13 right :lvalue t)
336 (binary-op >>>= ">>>=" 13 right :lvalue t)
338 (binary-op comma "," 13 right)
339 (binary-op progn "," 13 right)
341 (when (member op '(? if))
342 (when (low-precedence-p 12) (js-format "("))
343 (js-expr (first args) 12 'right 'left)
345 (js-expr (second args) 12 'right 'right)
347 (js-expr (third args) 12 'right 'right)
348 (when (low-precedence-p 12) (js-format ")"))
349 (return-from js-operator-expression))
351 (error "Unknown operator `~S'" op)))))))
353 (defun js-expr (form &optional (precedence 1000) associativity operand-order)
354 (let ((form (js-expand-expr form)))
356 ((or (symbolp form) (numberp form) (stringp form))
357 (js-primary-expr form))
359 (js-vector-initializer form))
361 (js-operator-expression (car form) (cdr form) precedence associativity operand-order)))))
363 (defun js-expand-stmt (form)
365 ((and (consp form) (eq (car form) 'progn))
366 (destructuring-bind (&body body) (cdr form)
371 (js-expand-stmt (car body)))
373 `(group ,@(cdr form))))))
375 (js-macroexpand form))))
377 (defun js-end-stmt ()
379 (when *js-pretty-print*
382 (defun js-stmt (form &optional parent)
383 (let ((form (js-expand-stmt form)))
384 (flet ((js-stmt (x) (js-stmt x form)))
387 (unless (or (and (consp parent) (eq (car parent) 'group))
397 (destructuring-bind (label &body body) (cdr form)
398 (js-identifier label)
400 (js-stmt `(progn ,@body))))
402 (destructuring-bind (&optional label) (cdr form)
406 (js-identifier label))
409 (destructuring-bind (value) (cdr form)
410 (js-format "return ")
414 (flet ((js-var (spec)
415 (destructuring-bind (variable &optional initial)
417 (js-identifier variable)
420 (js-expr initial no-comma)))))
421 (destructuring-bind (var &rest vars) (cdr form)
429 (destructuring-bind (condition true &optional false) (cdr form)
440 (and (consp parent) (eq (car parent) 'group)))))
441 (unless in-group-p (js-format "{"))
442 (mapc #'js-stmt (cdr form))
443 (unless in-group-p (js-format "}"))))
445 (destructuring-bind (condition &body body) (cdr form)
446 (js-format "while (")
449 (js-stmt `(progn ,@body))))
451 (destructuring-bind (value &rest cases) (cdr form)
452 (js-format "switch(")
457 ((and (consp case) (eq (car case) 'case))
459 (let ((value (cadr case)))
460 (unless (or (stringp value) (integerp value))
461 (error "Non-constant switch case `~S'." value))
465 (js-format "default:"))
470 (destructuring-bind ((start condition step) &body body) (cdr form)
478 (js-stmt `(progn ,@body))))
480 (destructuring-bind ((x object) &body body) (cdr form)
486 (js-stmt `(progn ,@body))))
488 (destructuring-bind (&rest body) (cdr form)
490 (js-stmt `(group ,@body))))
492 (destructuring-bind ((var) &rest body) (cdr form)
493 (js-format "catch (")
496 (js-stmt `(group ,@body))))
498 (destructuring-bind (&rest body) (cdr form)
499 (js-format "finally")
500 (js-stmt `(group ,@body))))
502 (destructuring-bind (object) (cdr form)
510 (defun js (&rest stmts)
511 (mapc #'js-stmt stmts)