Toplevel empty statement are empty strings
[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-output* t)
28
29 ;;; Two seperate functions are needed for escaping strings:
30 ;;;  One for producing JavaScript string literals (which are singly or
31 ;;;   doubly quoted)
32 ;;;  And one for producing Lisp strings (which are only doubly quoted)
33 ;;;
34 ;;; The same function would suffice for both, but for javascript string
35 ;;; literals it is neater to use either depending on the context, e.g:
36 ;;;  foo's => "foo's"
37 ;;;  "foo" => '"foo"'
38 ;;; which avoids having to escape quotes where possible
39 (defun js-escape-string (string)
40   (let ((index 0)
41         (size (length string))
42         (seen-single-quote nil)
43         (seen-double-quote nil))
44     (flet ((%js-escape-string (string escape-single-quote-p)
45              (let ((output "")
46                    (index 0))
47                (while (< index size)
48                  (let ((ch (char string index)))
49                    (when (char= ch #\\)
50                      (setq output (concat output "\\")))
51                    (when (and escape-single-quote-p (char= ch #\'))
52                      (setq output (concat output "\\")))
53                    (when (char= ch #\newline)
54                      (setq output (concat output "\\"))
55                      (setq ch #\n))
56                    (setq output (concat output (string ch))))
57                  (incf index))
58                output)))
59       ;; First, scan the string for single/double quotes
60       (while (< index size)
61         (let ((ch (char string index)))
62           (when (char= ch #\')
63             (setq seen-single-quote t))
64           (when (char= ch #\")
65             (setq seen-double-quote t)))
66         (incf index))
67       ;; Then pick the appropriate way to escape the quotes
68       (cond
69         ((not seen-single-quote)
70          (concat "'"   (%js-escape-string string nil) "'"))
71         ((not seen-double-quote)
72          (concat "\""  (%js-escape-string string nil) "\""))
73         (t (concat "'" (%js-escape-string string t)   "'"))))))
74
75
76 (defun js-format (fmt &rest args)
77   (apply #'format *js-output* fmt args))
78
79 (defun valid-js-identifier (string-designator)
80   (let ((string (typecase string-designator
81                   (symbol (string-downcase (symbol-name string-designator)))
82                   (string string-designator)
83                   (t
84                    (return-from valid-js-identifier (values nil nil))))))
85     (flet ((constitutentp (ch)
86              (or (alphanumericp ch) (member ch '(#\$ #\_)))))
87       (if (and (every #'constitutentp string)
88                (if (plusp (length string))
89                    (not (digit-char-p (char string 0)))
90                    t))
91           (values (format nil "~a" string) t)
92           (values nil nil)))))
93
94 (defun js-identifier (string-designator)
95   (multiple-value-bind (string valid)
96       (valid-js-identifier string-designator)
97     (unless valid
98       (error "~S is not a valid Javascript identifier." string))
99     (js-format "~a" string)))
100
101 (defun js-primary-expr (form)
102   (cond
103     ((numberp form)
104      (if (<= 0 form)
105          (js-format "~a" form)
106          (js-expr `(- ,(abs form)))))
107     ((stringp form)
108      (js-format "~a" (js-escape-string form)))
109     ((symbolp form)
110      (case form
111        (true  (js-format "true"))
112        (false (js-format "false"))
113        (null  (js-format "null"))
114        (this  (js-format "this"))
115        (otherwise
116         (js-identifier form))))
117     (t
118      (error "Unknown Javascript syntax ~S." form))))
119
120 (defun js-vector-initializer (vector)
121   (let ((size (length vector)))
122     (js-format "[")
123     (dotimes (i (1- size))
124       (let ((elt (aref vector i)))
125         (unless (eq elt 'null)
126           (js-expr elt))
127         (js-format ",")))
128     (when (plusp size)
129       (js-expr (aref vector (1- size))))
130     (js-format "]")))
131
132 (defun js-object-initializer (plist)
133   (js-format "{")
134   (do* ((tail plist (cddr tail)))
135        ((null tail))
136     (let ((key (car tail))
137           (value (cadr tail)))
138       (multiple-value-bind (identifier identifier-p) (valid-js-identifier key)
139         (declare (ignore identifier))
140         (if identifier-p
141             (js-identifier key)
142             (js-expr (string key))))
143       (js-format ": ")
144       (js-expr value)
145       (unless (null (cddr tail))
146         (js-format ","))))
147   (js-format "}"))
148
149 (defun js-function (arguments &rest body)
150   (js-format "function(")
151   (when arguments
152     (js-identifier (car arguments))
153     (dolist (arg (cdr arguments))
154       (js-format ",")
155       (js-identifier arg)))
156   (js-format ")")
157   (js-stmt `(group ,@body) t))
158
159 (defun check-lvalue (x)
160   (unless (or (symbolp x)
161               (nth-value 1 (valid-js-identifier x))
162               (and (consp x)
163                    (member (car x) '(get =))))
164     (error "Bad Javascript lvalue ~S" x)))
165
166 ;;; Process the Javascript AST to reduce some syntax sugar.
167 (defun js-expand-expr (form)
168   (if (consp form)
169       (case (car form)
170         (+
171          (case (length (cdr form))
172            (1 `(unary+ ,(cadr form)))
173            (t (reduce (lambda (x y) `(+ ,x ,y)) (cdr form)))))
174         (-
175          (case (length (cdr form))
176            (1 `(unary- ,(cadr form)))
177            (t (reduce (lambda (x y) `(- ,x ,y)) (cdr form)))))
178         ((progn comma)
179          (reduce (lambda (x y) `(comma ,x ,y)) (cdr form) :from-end t))
180         (t form))
181       form))
182
183 ;; Initialized to any value larger than any operator precedence
184 (defvar *js-operator-precedence* 1000)
185 (defvar *js-operator-associativity* 'left)
186 (defvar *js-operand-order* 'left)
187
188 ;; Format an expression optionally wrapped with parenthesis if the
189 ;; precedence rules require it.
190 (defmacro with-operator ((precedence associativity) &body body)
191   (let ((g!parens (gensym))
192         (g!precedence (gensym)))
193     `(let* ((,g!precedence ,precedence)
194             (,g!parens
195              (cond
196                ((> ,g!precedence *js-operator-precedence*))
197                ((< ,g!precedence *js-operator-precedence*) nil)
198                ;; Same precedence. Let us consider associativity.
199                (t
200                 (not (eq *js-operand-order* *js-operator-associativity*)))))
201             (*js-operator-precedence* ,g!precedence)
202             (*js-operator-associativity* ,associativity)
203             (*js-operand-order* 'left))
204        (when ,g!parens (js-format "("))
205        (progn ,@body)
206        (when ,g!parens (js-format ")")))))
207
208 (defun js-operator (string)
209   (js-format "~a" string)
210   (setq *js-operand-order* 'right))
211
212 (defun js-operator-expression (op args)
213   (let ((op1 (car args))
214         (op2 (cadr args)))
215     (case op
216       ;; Transactional compatible operator
217       (code
218        (js-format "~a" (apply #'code args)))
219       ;; Function call
220       (call
221        (js-expr (car args))
222        (js-format "(")
223        (when (cdr args)
224          (with-operator (13 'left)
225            (js-expr (cadr args))
226            (dolist (operand (cddr args))
227              (let ((*js-output* t))
228                (js-format ",")
229                (js-expr operand)))))
230        (js-format ")"))
231       ;; Accessors
232       (get
233        (multiple-value-bind (identifier identifierp)
234            (valid-js-identifier (car args))
235          (multiple-value-bind (accessor accessorp)
236              (valid-js-identifier (cadr args))
237            (cond
238              ((and identifierp accessorp)
239               (js-identifier identifier)
240               (js-format ".")
241               (js-identifier accessor))
242              (t
243               (js-expr (car args))
244               (js-format "[")
245               (js-expr (cadr args))
246               (js-format "]"))))))
247       ;; Object syntax
248       (object
249        (js-object-initializer args))
250       ;; Function expressions
251       (function
252        (js-format "(")
253        (apply #'js-function args)
254        (js-format ")"))
255       (t
256        (flet ((%unary-op (operator string precedence associativity post lvalue)
257                 (when (eq op operator)
258                   (with-operator (precedence associativity)
259                     (when lvalue (check-lvalue op1))
260                     (cond
261                       (post
262                        (js-expr op1)
263                        (js-operator string))
264                       (t
265                        (js-operator string)
266                        (js-expr op1))))
267                   (return-from js-operator-expression)))
268               (%binary-op (operator string precedence associativity lvalue)
269                 (when (eq op operator)
270                   (when lvalue (check-lvalue op1))
271                   (with-operator (precedence associativity)
272                     (js-expr op1)
273                     (js-operator string)
274                     (js-expr op2))
275                   (return-from js-operator-expression))))
276
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)))
281
282            (unary-op pre++       "++"            1    right :lvalue t)
283            (unary-op pre--       "--"            1    right :lvalue t)
284            (unary-op post++      "++"            1    right :lvalue t :post t)
285            (unary-op post--      "--"            1    right :lvalue t :post t)
286            (unary-op not         "!"             1    right)
287            (unary-op bit-not     "~"             1    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+      " +"            1    right)
292            (unary-op unary-      " -"            1    right)
293            (unary-op delete      "delete "       1    right)
294            (unary-op void        "void "         1    right)
295            (unary-op typeof      "typeof "       1    right)
296            (unary-op new         "new "          1    right)
297
298            (binary-op *          "*"             2    left)
299            (binary-op /          "/"             2    left)
300            (binary-op mod        "%"             2    left)
301            (binary-op %          "%"             2    left)
302            (binary-op +          "+"             3    left)
303            (binary-op -          "-"             3    left)
304            (binary-op <<         "<<"            4    left)
305            (binary-op >>         "<<"            4    left)
306            (binary-op >>>        ">>>"           4    left)
307            (binary-op <=         "<="            5    left)
308            (binary-op <          "<"             5    left)
309            (binary-op >          ">"             5    left)
310            (binary-op >=         ">="            5    left)
311            (binary-op instanceof " instanceof "  5    left)
312            (binary-op in         " in "          5    left)
313            (binary-op ==         "=="            6    left)
314            (binary-op !=         "!="            6    left)
315            (binary-op ===        "==="           6    left)
316            (binary-op !==        "!=="           6    left)
317            (binary-op bit-and    "&"             7    left)
318            (binary-op bit-xor    "^"             8    left)
319            (binary-op bit-or     "|"             9    left)
320            (binary-op and        "&&"           10    left)
321            (binary-op or         "||"           11    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)
335
336            (binary-op comma      ","            13    right)
337            (binary-op progn      ","            13    right)
338
339            (when (member op '(? if))
340              (with-operator (12 'right)
341                (js-expr (first args))
342                (js-operator "?")
343                (js-expr (second args))
344                (js-format ":")
345                (js-expr (third args)))
346              (return-from js-operator-expression))
347
348            (error "Unknown operator `~S'" op)))))))
349
350 (defun js-expr (form)
351   (let ((form (js-expand-expr form)))
352     (cond
353       ((or (symbolp form) (numberp form) (stringp form))
354        (js-primary-expr form))
355       ((vectorp form)
356        (js-vector-initializer form))
357       (t
358        (js-operator-expression (car form) (cdr form))))))
359
360 (defun js-expand-stmt (form)
361   (cond
362     ((and (consp form) (eq (car form) 'progn))
363      (destructuring-bind (&body body) (cdr form)
364        (cond
365          ((null body)
366           nil)
367          ((null (cdr body))
368           (js-expand-stmt (car body)))
369          (t
370           `(group ,@(cdr form))))))
371     (t
372      form)))
373
374 (defun js-stmt (form &optional parent)
375   (let ((form (js-expand-stmt form)))
376     (flet ((js-stmt (x) (js-stmt x form)))
377       (cond
378         ((null form)
379          (unless (or (and (consp parent) (eq (car parent) 'group))
380                      (null parent))
381            (js-format ";")))
382         ((atom form)
383          (progn
384            (js-expr form)
385            (js-format ";")))
386         (t
387          (case (car form)
388            (code
389             (js-format "~a" (apply #'code (cdr form))))
390            (label
391             (destructuring-bind (label &body body) (cdr form)
392               (js-identifier label)
393               (js-format ":")
394               (js-stmt `(progn ,@body))))
395            (break
396             (destructuring-bind (label) (cdr form)
397               (js-format "break ")
398               (js-identifier label)
399               (js-format ";")))
400            (return
401              (destructuring-bind (value) (cdr form)
402                (js-format "return ")
403                (js-expr value)
404                (js-format ";")))
405            (var
406             (flet ((js-var (spec)
407                      (destructuring-bind (variable &optional initial)
408                          (ensure-list spec)
409                        (js-identifier variable)
410                        (when initial
411                          (js-format "=")
412                          (js-expr initial)))))
413               (destructuring-bind (var &rest vars) (cdr form)
414                 (let ((*js-operator-precedence* 12))
415                   (js-format "var ")
416                   (js-var var)
417                   (dolist (var vars)
418                     (js-format ",")
419                     (js-var var))
420                   (js-format ";")))))
421            (if
422             (destructuring-bind (condition true &optional false) (cdr form)
423               (js-format "if (")
424               (js-expr condition)
425               (js-format ") ")
426               (js-stmt true)
427               (when false
428                 (js-format " else ")
429                 (js-stmt false))))
430            (group
431             (let ((in-group-p
432                    (or (null parent)
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 "}"))))
437            (while
438                (destructuring-bind (condition &body body) (cdr form)
439                  (js-format "while (")
440                  (js-expr condition)
441                  (js-format ")")
442                  (js-stmt `(progn ,@body))))
443            (throw
444                (destructuring-bind (object) (cdr form)
445                  (js-format "throw ")
446                  (js-expr object)
447                  (js-format ";")))
448            (t
449             (js-expr form)
450             (js-format ";"))))))))
451
452 (defun js (&rest stmts)
453   (mapc #'js-stmt stmts)
454   nil)