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 ;;; Two seperate functions are needed for escaping strings:
53 ;;; One for producing JavaScript string literals (which are singly or
55 ;;; And one for producing Lisp strings (which are only doubly quoted)
57 ;;; The same function would suffice for both, but for javascript string
58 ;;; literals it is neater to use either depending on the context, e.g:
61 ;;; which avoids having to escape quotes where possible
62 (defun js-escape-string (string)
64 (size (length string))
65 (seen-single-quote nil)
66 (seen-double-quote nil))
67 (flet ((%js-escape-string (string escape-single-quote-p)
71 (let ((ch (char string index)))
73 (setq output (concat output "\\")))
74 (when (and escape-single-quote-p (char= ch #\'))
75 (setq output (concat output "\\")))
76 (when (char= ch #\newline)
77 (setq output (concat output "\\"))
79 (setq output (concat output (string ch))))
82 ;; First, scan the string for single/double quotes
84 (let ((ch (char string index)))
86 (setq seen-single-quote t))
88 (setq seen-double-quote t)))
90 ;; Then pick the appropriate way to escape the quotes
92 ((not seen-single-quote)
93 (concat "'" (%js-escape-string string nil) "'"))
94 ((not seen-double-quote)
95 (concat "\"" (%js-escape-string string nil) "\""))
96 (t (concat "'" (%js-escape-string string t) "'"))))))
99 (defun js-format (fmt &rest args)
100 (apply #'format *js-output* fmt args))
102 (defun valid-js-identifier (string-designator)
103 (let ((string (typecase string-designator
104 (symbol (symbol-name string-designator))
105 (string string-designator)
107 (return-from valid-js-identifier (values nil nil))))))
108 (flet ((constitutentp (ch)
109 (or (alphanumericp ch) (member ch '(#\$ #\_)))))
110 (if (and (every #'constitutentp string)
111 (if (plusp (length string))
112 (not (digit-char-p (char string 0)))
114 (values (format nil "~a" string) t)
117 (defun js-identifier (string-designator)
118 (multiple-value-bind (string valid)
119 (valid-js-identifier string-designator)
121 (error "~S is not a valid Javascript identifier." string))
122 (js-format "~a" string)))
124 (defun js-primary-expr (form)
128 (js-format "~a" form)
129 (js-expr `(- ,(abs form)))))
131 (js-format "~a" (js-escape-string form)))
134 (true (js-format "true"))
135 (false (js-format "false"))
136 (null (js-format "null"))
137 (this (js-format "this"))
138 (undefined (js-format "undefined"))
140 (js-identifier form))))
142 (error "Unknown Javascript syntax ~S." form))))
144 (defun js-vector-initializer (vector)
145 (let ((size (length vector)))
147 (dotimes (i (1- size))
148 (let ((elt (aref vector i)))
149 (unless (eq elt 'null)
150 (js-expr elt no-comma))
153 (js-expr (aref vector (1- size)) no-comma))
156 (defun js-object-initializer (plist)
158 (do* ((tail plist (cddr tail)))
160 (let ((key (car tail))
162 (multiple-value-bind (identifier identifier-p) (valid-js-identifier key)
163 (declare (ignore identifier))
166 (js-expr (string key) no-comma)))
168 (js-expr value no-comma)
169 (unless (null (cddr tail))
173 (defun js-function (arguments &rest body)
174 (js-format "function(")
176 (js-identifier (car arguments))
177 (dolist (arg (cdr arguments))
179 (js-identifier arg)))
181 (js-stmt `(group ,@body) t))
183 (defun check-lvalue (x)
184 (unless (or (symbolp x)
185 (nth-value 1 (valid-js-identifier x))
187 (member (car x) '(get = property))))
188 (error "Bad Javascript lvalue ~S" x)))
190 ;;; Process the Javascript AST to reduce some syntax sugar.
191 (defun js-expand-expr (form)
195 (case (length (cdr form))
196 (1 `(unary+ ,(cadr form)))
197 (t (reduce (lambda (x y) `(+ ,x ,y)) (cdr form)))))
199 (case (length (cdr form))
200 (1 `(unary- ,(cadr form)))
201 (t (reduce (lambda (x y) `(- ,x ,y)) (cdr form)))))
203 (reduce (lambda (x y) `(,(car form) ,x ,y)) (cdr form)))
205 (reduce (lambda (x y) `(comma ,x ,y)) (cdr form) :from-end t))
207 (js-macroexpand form)))
210 (defun js-operator-expression (op args precedence associativity operand-order)
211 (let ((op1 (car args))
216 (js-expr (car args) 0)
218 (js-expr (cadr args) no-comma)
221 (multiple-value-bind (accessor accessorp)
222 (valid-js-identifier (cadr args))
224 (error "Invalid accessor ~S" (cadr args)))
225 (js-expr (car args) 0)
227 (js-identifier accessor)))
230 (js-expr (car args) 1)
233 (js-expr (cadr args) no-comma)
234 (dolist (operand (cddr args))
236 (js-expr operand no-comma)))
240 (js-object-initializer args))
241 ;; Function expressions
244 (apply #'js-function args)
247 (labels ((low-precedence-p (op-precedence)
249 ((> op-precedence precedence))
250 ((< op-precedence precedence) nil)
251 (t (not (eq operand-order associativity)))))
253 (%unary-op (operator string operator-precedence operator-associativity post lvalue)
254 (when (eq op operator)
255 (when lvalue (check-lvalue op1))
256 (when (low-precedence-p operator-precedence) (js-format "("))
259 (js-expr op1 operator-precedence operator-associativity 'left)
260 (js-format "~a" string))
262 (js-format "~a" string)
263 (js-expr op1 operator-precedence operator-associativity 'right)))
264 (when (low-precedence-p operator-precedence) (js-format ")"))
265 (return-from js-operator-expression)))
267 (%binary-op (operator string operator-precedence operator-associativity lvalue)
268 (when (eq op operator)
269 (when lvalue (check-lvalue op1))
270 (when (low-precedence-p operator-precedence) (js-format "("))
271 (js-expr op1 operator-precedence operator-associativity 'left)
272 (js-format "~a" string)
273 (js-expr op2 operator-precedence operator-associativity 'right)
274 (when (low-precedence-p operator-precedence) (js-format ")"))
275 (return-from js-operator-expression))))
277 (macrolet ((unary-op (operator string precedence associativity &key post lvalue)
278 `(%unary-op ',operator ',string ',precedence ',associativity ',post ',lvalue))
279 (binary-op (operator string precedence associativity &key lvalue)
280 `(%binary-op ',operator ',string ',precedence ',associativity ',lvalue)))
282 (unary-op pre++ "++" 2 right :lvalue t)
283 (unary-op pre-- "--" 2 right :lvalue t)
284 (unary-op post++ "++" 2 right :lvalue t :post t)
285 (unary-op post-- "--" 2 right :lvalue t :post t)
286 (unary-op not "!" 2 right)
287 (unary-op bit-not "~" 2 right)
288 ;; Note that the leading space is necessary because it
289 ;; could break with post++, for example. TODO: Avoid
290 ;; leading space when it's possible.
291 (unary-op unary+ " +" 2 right)
292 (unary-op unary- " -" 2 right)
293 (unary-op delete "delete " 2 right)
294 (unary-op void "void " 2 right)
295 (unary-op typeof "typeof " 2 right)
296 (unary-op new "new " 2 right)
298 (binary-op * "*" 3 left)
299 (binary-op / "/" 3 left)
300 (binary-op mod "%" 3 left)
301 (binary-op % "%" 3 left)
302 (binary-op + "+" 4 left)
303 (binary-op - "-" 5 left)
304 (binary-op << "<<" 5 left)
305 (binary-op >> "<<" 5 left)
306 (binary-op >>> ">>>" 5 left)
307 (binary-op <= "<=" 6 left)
308 (binary-op < "<" 6 left)
309 (binary-op > ">" 6 left)
310 (binary-op >= ">=" 6 left)
311 (binary-op instanceof " instanceof " 6 left)
312 (binary-op in " in " 6 left)
313 (binary-op == "==" 7 left)
314 (binary-op != "!=" 7 left)
315 (binary-op === "===" 7 left)
316 (binary-op !== "!==" 7 left)
317 (binary-op bit-and "&" 8 left)
318 (binary-op bit-xor "^" 9 left)
319 (binary-op bit-or "|" 10 left)
320 (binary-op and "&&" 11 left)
321 (binary-op or "||" 12 left)
322 (binary-op = "=" 13 right :lvalue t)
323 (binary-op += "+=" 13 right :lvalue t)
324 (binary-op incf "+=" 13 right :lvalue t)
325 (binary-op -= "-=" 13 right :lvalue t)
326 (binary-op decf "-=" 13 right :lvalue t)
327 (binary-op *= "*=" 13 right :lvalue t)
328 (binary-op /= "*=" 13 right :lvalue t)
329 (binary-op bit-xor= "^=" 13 right :lvalue t)
330 (binary-op bit-and= "&=" 13 right :lvalue t)
331 (binary-op bit-or= "|=" 13 right :lvalue t)
332 (binary-op <<= "<<=" 13 right :lvalue t)
333 (binary-op >>= ">>=" 13 right :lvalue t)
334 (binary-op >>>= ">>>=" 13 right :lvalue t)
336 (binary-op comma "," 13 right)
337 (binary-op progn "," 13 right)
339 (when (member op '(? if))
340 (when (low-precedence-p 12) (js-format "("))
341 (js-expr (first args) 12 'right 'left)
343 (js-expr (second args) 12 'right 'right)
345 (js-expr (third args) 12 'right 'right)
346 (when (low-precedence-p 12) (js-format ")"))
347 (return-from js-operator-expression))
349 (error "Unknown operator `~S'" op)))))))
351 (defun js-expr (form &optional (precedence 1000) associativity operand-order)
352 (let ((form (js-expand-expr form)))
354 ((or (symbolp form) (numberp form) (stringp form))
355 (js-primary-expr form))
357 (js-vector-initializer form))
359 (js-operator-expression (car form) (cdr form) precedence associativity operand-order)))))
361 (defun js-expand-stmt (form)
363 ((and (consp form) (eq (car form) 'progn))
364 (destructuring-bind (&body body) (cdr form)
369 (js-expand-stmt (car body)))
371 `(group ,@(cdr form))))))
373 (js-macroexpand form))))
375 (defun js-stmt (form &optional parent)
376 (let ((form (js-expand-stmt form)))
377 (flet ((js-stmt (x) (js-stmt x form)))
380 (unless (or (and (consp parent) (eq (car parent) 'group))
390 (destructuring-bind (label &body body) (cdr form)
391 (js-identifier label)
393 (js-stmt `(progn ,@body))))
395 (destructuring-bind (&optional label) (cdr form)
399 (js-identifier label))
402 (destructuring-bind (value) (cdr form)
403 (js-format "return ")
407 (flet ((js-var (spec)
408 (destructuring-bind (variable &optional initial)
410 (js-identifier variable)
413 (js-expr initial no-comma)))))
414 (destructuring-bind (var &rest vars) (cdr form)
422 (destructuring-bind (condition true &optional false) (cdr form)
433 (and (consp parent) (eq (car parent) 'group)))))
434 (unless in-group-p (js-format "{"))
435 (mapc #'js-stmt (cdr form))
436 (unless in-group-p (js-format "}"))))
438 (destructuring-bind (condition &body body) (cdr form)
439 (js-format "while (")
442 (js-stmt `(progn ,@body))))
444 (destructuring-bind (value &rest cases) (cdr form)
445 (js-format "switch(")
450 ((and (consp case) (eq (car case) 'case))
452 (let ((value (cadr case)))
453 (unless (or (stringp value) (integerp value))
454 (error "Non-constant switch case `~S'." value))
458 (js-format "default:"))
463 (destructuring-bind ((start condition step) &body body) (cdr form)
471 (js-stmt `(progn ,@body))))
473 (destructuring-bind ((x object) &body body) (cdr form)
479 (js-stmt `(progn ,@body))))
481 (destructuring-bind (&rest body) (cdr form)
483 (js-stmt `(group ,@body))))
485 (destructuring-bind ((var) &rest body) (cdr form)
486 (js-format "catch (")
489 (js-stmt `(group ,@body))))
491 (destructuring-bind (&rest body) (cdr form)
492 (js-format "finally")
493 (js-stmt `(group ,@body))))
495 (destructuring-bind (object) (cdr form)
501 (js-format ";"))))))))
503 (defun js (&rest stmts)
504 (mapc #'js-stmt stmts)