Secondary value in js macroexpanders to inhibit macroexpansion
[jscl.git] / src / compiler-codegen.lisp
1 ;;; compiler-codege.lisp --- Naive Javascript unparser
2
3 ;; copyright (C) 2013 David Vazquez
4
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.
9 ;;
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.
14 ;;
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/>.
17
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.
21 ;;;
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.
24
25 (/debug "loading compiler-codegen.lisp!")
26
27 (defvar *js-macros* nil)
28 (defmacro define-js-macro (name lambda-list &body body)
29   (let ((form (gensym)))
30     `(push (cons ',name
31                  (lambda (,form)
32                    (block ,name
33                      (destructuring-bind ,lambda-list ,form
34                        ,@body))))
35            *js-macros*)))
36
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))
42           (if stop-expand-p
43               expansion
44               (js-macroexpand expansion))))
45       js))
46
47
48 (defconstant no-comma 12)
49
50 (defvar *js-output* t)
51
52 ;;; Two seperate functions are needed for escaping strings:
53 ;;;  One for producing JavaScript string literals (which are singly or
54 ;;;   doubly quoted)
55 ;;;  And one for producing Lisp strings (which are only doubly quoted)
56 ;;;
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:
59 ;;;  foo's => "foo's"
60 ;;;  "foo" => '"foo"'
61 ;;; which avoids having to escape quotes where possible
62 (defun js-escape-string (string)
63   (let ((index 0)
64         (size (length string))
65         (seen-single-quote nil)
66         (seen-double-quote nil))
67     (flet ((%js-escape-string (string escape-single-quote-p)
68              (let ((output "")
69                    (index 0))
70                (while (< index size)
71                  (let ((ch (char string index)))
72                    (when (char= ch #\\)
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 "\\"))
78                      (setq ch #\n))
79                    (setq output (concat output (string ch))))
80                  (incf index))
81                output)))
82       ;; First, scan the string for single/double quotes
83       (while (< index size)
84         (let ((ch (char string index)))
85           (when (char= ch #\')
86             (setq seen-single-quote t))
87           (when (char= ch #\")
88             (setq seen-double-quote t)))
89         (incf index))
90       ;; Then pick the appropriate way to escape the quotes
91       (cond
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)   "'"))))))
97
98
99 (defun js-format (fmt &rest args)
100   (apply #'format *js-output* fmt args))
101
102 (defun valid-js-identifier (string-designator)
103   (let ((string (typecase string-designator
104                   (symbol (symbol-name string-designator))
105                   (string string-designator)
106                   (t
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)))
113                    t))
114           (values (format nil "~a" string) t)
115           (values nil nil)))))
116
117 (defun js-identifier (string-designator)
118   (multiple-value-bind (string valid)
119       (valid-js-identifier string-designator)
120     (unless valid
121       (error "~S is not a valid Javascript identifier." string))
122     (js-format "~a" string)))
123
124 (defun js-primary-expr (form)
125   (cond
126     ((numberp form)
127      (if (<= 0 form)
128          (js-format "~a" form)
129          (js-expr `(- ,(abs form)))))
130     ((stringp form)
131      (js-format "~a" (js-escape-string form)))
132     ((symbolp form)
133      (case 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"))
139        (otherwise
140         (js-identifier form))))
141     (t
142      (error "Unknown Javascript syntax ~S." form))))
143
144 (defun js-vector-initializer (vector)
145   (let ((size (length vector)))
146     (js-format "[")
147     (dotimes (i (1- size))
148       (let ((elt (aref vector i)))
149         (unless (eq elt 'null)
150           (js-expr elt no-comma))
151         (js-format ",")))
152     (when (plusp size)
153       (js-expr (aref vector (1- size)) no-comma))
154     (js-format "]")))
155
156 (defun js-object-initializer (plist)
157   (js-format "{")
158   (do* ((tail plist (cddr tail)))
159        ((null tail))
160     (let ((key (car tail))
161           (value (cadr tail)))
162       (multiple-value-bind (identifier identifier-p) (valid-js-identifier key)
163         (declare (ignore identifier))
164         (if identifier-p
165             (js-identifier key)
166             (js-expr (string key) no-comma)))
167       (js-format ": ")
168       (js-expr value no-comma)
169       (unless (null (cddr tail))
170         (js-format ","))))
171   (js-format "}"))
172
173 (defun js-function (arguments &rest body)
174   (js-format "function(")
175   (when arguments
176     (js-identifier (car arguments))
177     (dolist (arg (cdr arguments))
178       (js-format ",")
179       (js-identifier arg)))
180   (js-format ")")
181   (js-stmt `(group ,@body) t))
182
183 (defun check-lvalue (x)
184   (unless (or (symbolp x)
185               (nth-value 1 (valid-js-identifier x))
186               (and (consp x)
187                    (member (car x) '(get = property))))
188     (error "Bad Javascript lvalue ~S" x)))
189
190 ;;; Process the Javascript AST to reduce some syntax sugar.
191 (defun js-expand-expr (form)
192   (if (consp form)
193       (case (car form)
194         (+
195          (case (length (cdr form))
196            (1 `(unary+ ,(cadr form)))
197            (t (reduce (lambda (x y) `(+ ,x ,y)) (cdr form)))))
198         (-
199          (case (length (cdr form))
200            (1 `(unary- ,(cadr form)))
201            (t (reduce (lambda (x y) `(- ,x ,y)) (cdr form)))))
202         ((and or)
203          (reduce (lambda (x y) `(,(car form) ,x ,y)) (cdr form)))
204         ((progn comma)
205          (reduce (lambda (x y) `(comma ,x ,y)) (cdr form) :from-end t))
206         (t
207          (js-macroexpand form)))
208       form))
209
210 (defun js-operator-expression (op args precedence associativity operand-order)
211   (let ((op1 (car args))
212         (op2 (cadr args)))
213     (case op
214       ;; Transactional compatible operator
215       (code
216        (js-format "~a" (apply #'code args)))
217       ;; Accessors
218       (property
219        (js-expr (car args) 0)
220        (js-format "[")
221        (js-expr (cadr args) no-comma)
222        (js-format "]"))
223       (get
224        (multiple-value-bind (accessor accessorp)
225            (valid-js-identifier (cadr args))
226          (unless accessorp
227            (error "Invalid accessor ~S" (cadr args)))
228          (js-expr (car args) 0)
229          (js-format ".")
230          (js-identifier accessor)))      
231       ;; Function call
232       (call
233        (js-expr (car args) 1)
234        (js-format "(")
235        (when (cdr args)
236          (js-expr (cadr args) no-comma)
237          (dolist (operand (cddr args))
238            (js-format ",")
239            (js-expr operand no-comma)))
240        (js-format ")"))
241       ;; Object syntax
242       (object
243        (js-object-initializer args))
244       ;; Function expressions
245       (function
246        (js-format "(")
247        (apply #'js-function args)
248        (js-format ")"))
249       (t
250        (labels ((low-precedence-p (op-precedence)
251                   (cond
252                     ((> op-precedence precedence))
253                     ((< op-precedence precedence) nil)
254                     (t (not (eq operand-order associativity)))))
255                 
256                 (%unary-op (operator string operator-precedence operator-associativity post lvalue)
257                   (when (eq op operator)
258                     (when lvalue (check-lvalue op1))
259                     (when (low-precedence-p operator-precedence) (js-format "("))
260                     (cond
261                       (post
262                        (js-expr op1 operator-precedence operator-associativity 'left)
263                        (js-format "~a" string))
264                       (t
265                        (js-format "~a" string)
266                        (js-expr op1 operator-precedence operator-associativity 'right)))
267                     (when (low-precedence-p operator-precedence) (js-format ")"))
268                     (return-from js-operator-expression)))
269                 
270                 (%binary-op (operator string operator-precedence operator-associativity lvalue)
271                   (when (eq op operator)
272                     (when lvalue (check-lvalue op1))
273                     (when (low-precedence-p operator-precedence) (js-format "("))
274                     (js-expr op1 operator-precedence operator-associativity 'left)
275                     (js-format "~a" string)
276                     (js-expr op2 operator-precedence operator-associativity 'right)
277                     (when (low-precedence-p operator-precedence) (js-format ")"))
278                     (return-from js-operator-expression))))
279
280          (macrolet ((unary-op (operator string precedence associativity &key post lvalue)
281                       `(%unary-op ',operator ',string ',precedence ',associativity ',post ',lvalue))
282                     (binary-op (operator string precedence associativity &key lvalue)
283                       `(%binary-op ',operator ',string ',precedence ',associativity ',lvalue)))
284
285            (unary-op pre++       "++"            2    right :lvalue t)
286            (unary-op pre--       "--"            2    right :lvalue t)
287            (unary-op post++      "++"            2    right :lvalue t :post t)
288            (unary-op post--      "--"            2    right :lvalue t :post t)
289            (unary-op not         "!"             2    right)
290            (unary-op bit-not     "~"             2    right)
291            ;; Note that the leading space is necessary because it
292            ;; could break with post++, for example. TODO: Avoid
293            ;; leading space when it's possible.
294            (unary-op unary+      " +"            2    right)
295            (unary-op unary-      " -"            2    right)
296            (unary-op delete      "delete "       2    right)
297            (unary-op void        "void "         2    right)
298            (unary-op typeof      "typeof "       2    right)
299            (unary-op new         "new "          2    right)
300
301            (binary-op *          "*"             3    left)
302            (binary-op /          "/"             3    left)
303            (binary-op mod        "%"             3    left)
304            (binary-op %          "%"             3    left)
305            (binary-op +          "+"             4    left)
306            (binary-op -          "-"             5    left)
307            (binary-op <<         "<<"            5    left)
308            (binary-op >>         "<<"            5    left)
309            (binary-op >>>        ">>>"           5    left)
310            (binary-op <=         "<="            6    left)
311            (binary-op <          "<"             6    left)
312            (binary-op >          ">"             6    left)
313            (binary-op >=         ">="            6    left)
314            (binary-op instanceof " instanceof "  6    left)
315            (binary-op in         " in "          6    left)
316            (binary-op ==         "=="            7    left)
317            (binary-op !=         "!="            7    left)
318            (binary-op ===        "==="           7    left)
319            (binary-op !==        "!=="           7    left)
320            (binary-op bit-and    "&"             8    left)
321            (binary-op bit-xor    "^"             9    left)
322            (binary-op bit-or     "|"            10    left)
323            (binary-op and        "&&"           11    left)
324            (binary-op or         "||"           12    left)
325            (binary-op =          "="            13    right :lvalue t)
326            (binary-op +=         "+="           13    right :lvalue t)
327            (binary-op incf       "+="           13    right :lvalue t)
328            (binary-op -=         "-="           13    right :lvalue t)
329            (binary-op decf       "-="           13    right :lvalue t)
330            (binary-op *=         "*="           13    right :lvalue t)
331            (binary-op /=         "*="           13    right :lvalue t)
332            (binary-op bit-xor=   "^="           13    right :lvalue t)
333            (binary-op bit-and=   "&="           13    right :lvalue t)
334            (binary-op bit-or=    "|="           13    right :lvalue t)
335            (binary-op <<=        "<<="          13    right :lvalue t)
336            (binary-op >>=        ">>="          13    right :lvalue t)
337            (binary-op >>>=       ">>>="         13    right :lvalue t)
338
339            (binary-op comma      ","            13    right)
340            (binary-op progn      ","            13    right)
341
342            (when (member op '(? if))
343              (when (low-precedence-p 12) (js-format "("))
344              (js-expr (first args) 12 'right 'left)
345              (js-format "?")
346              (js-expr (second args) 12 'right 'right)
347              (js-format ":")
348              (js-expr (third args) 12 'right 'right)
349              (when (low-precedence-p 12) (js-format ")"))
350              (return-from js-operator-expression))
351
352            (error "Unknown operator `~S'" op)))))))
353
354 (defun js-expr (form &optional (precedence 1000) associativity operand-order)
355   (let ((form (js-expand-expr form)))
356     (cond
357       ((or (symbolp form) (numberp form) (stringp form))
358        (js-primary-expr form))
359       ((vectorp form)
360        (js-vector-initializer form))
361       (t
362        (js-operator-expression (car form) (cdr form) precedence associativity operand-order)))))
363
364 (defun js-expand-stmt (form)
365   (cond
366     ((and (consp form) (eq (car form) 'progn))
367      (destructuring-bind (&body body) (cdr form)
368        (cond
369          ((null body)
370           nil)
371          ((null (cdr body))
372           (js-expand-stmt (car body)))
373          (t
374           `(group ,@(cdr form))))))
375     (t
376      (js-macroexpand form))))
377
378 (defun js-stmt (form &optional parent)
379   (let ((form (js-expand-stmt form)))
380     (flet ((js-stmt (x) (js-stmt x form)))
381       (cond
382         ((null form)
383          (unless (or (and (consp parent) (eq (car parent) 'group))
384                      (null parent))
385            (js-format ";")))
386         ((atom form)
387          (progn
388            (js-expr form)
389            (js-format ";")))
390         (t
391          (case (car form)
392            (code
393             (js-format "~a" (apply #'code (cdr form))))
394            (label
395             (destructuring-bind (label &body body) (cdr form)
396               (js-identifier label)
397               (js-format ":")
398               (js-stmt `(progn ,@body))))
399            (break
400             (destructuring-bind (&optional label) (cdr form)
401               (js-format "break")
402               (when label
403                 (js-format " ")
404                 (js-identifier label))
405               (js-format ";")))
406            (return
407              (destructuring-bind (value) (cdr form)
408                (js-format "return ")
409                (js-expr value)
410                (js-format ";")))
411            (var
412             (flet ((js-var (spec)
413                      (destructuring-bind (variable &optional initial)
414                          (ensure-list spec)
415                        (js-identifier variable)
416                        (when initial
417                          (js-format "=")
418                          (js-expr initial no-comma)))))
419               (destructuring-bind (var &rest vars) (cdr form)
420                 (js-format "var ")
421                 (js-var var)
422                 (dolist (var vars)
423                   (js-format ",")
424                   (js-var var))
425                 (js-format ";"))))
426            (if
427             (destructuring-bind (condition true &optional false) (cdr form)
428               (js-format "if (")
429               (js-expr condition)
430               (js-format ") ")
431               (js-stmt true)
432               (when false
433                 (js-format " else ")
434                 (js-stmt false))))
435            (group
436             (let ((in-group-p
437                    (or (null parent)
438                        (and (consp parent) (eq (car parent) 'group)))))
439               (unless  in-group-p (js-format "{"))
440               (mapc #'js-stmt (cdr form))
441               (unless in-group-p (js-format "}"))))
442            (while
443                (destructuring-bind (condition &body body) (cdr form)
444                  (js-format "while (")
445                  (js-expr condition)
446                  (js-format ")")
447                  (js-stmt `(progn ,@body))))
448            (switch
449             (destructuring-bind (value &rest cases) (cdr form)
450               (js-format "switch(")
451               (js-expr value)
452               (js-format "){")
453               (dolist (case cases)
454                 (cond
455                   ((and (consp case) (eq (car case) 'case))
456                    (js-format "case ")
457                    (let ((value (cadr case)))
458                      (unless (or (stringp value) (integerp value))
459                        (error "Non-constant switch case `~S'." value))
460                      (js-expr value))
461                    (js-format ":"))
462                   ((eq case 'default)
463                    (js-format "default:"))
464                   (t
465                    (js-stmt case))))
466               (js-format "}")))
467            (for
468             (destructuring-bind ((start condition step) &body body) (cdr form)
469               (js-format "for (")
470               (js-expr start)
471               (js-format ";")
472               (js-expr condition)
473               (js-format ";")
474               (js-expr step)
475               (js-format ")")
476               (js-stmt `(progn ,@body))))
477            (for-in
478             (destructuring-bind ((x object) &body body) (cdr form)
479               (js-format "for (")
480               (js-identifier x)
481               (js-format " in ")
482               (js-expr object)
483               (js-format ")")
484               (js-stmt `(progn ,@body))))
485            (try
486             (destructuring-bind (&rest body) (cdr form)
487               (js-format "try")
488               (js-stmt `(group ,@body))))
489            (catch
490                (destructuring-bind ((var) &rest body) (cdr form)
491                  (js-format "catch (")
492                  (js-identifier var)
493                  (js-format ")")
494                  (js-stmt `(group ,@body))))
495            (finally
496             (destructuring-bind (&rest body) (cdr form)
497               (js-format "finally")
498               (js-stmt `(group ,@body))))
499            (throw
500                (destructuring-bind (object) (cdr form)
501                  (js-format "throw ")
502                  (js-expr object)
503                  (js-format ";")))
504            (t
505             (js-expr form)
506             (js-format ";"))))))))
507
508 (defun js (&rest stmts)
509   (mapc #'js-stmt stmts)
510   nil)