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