61c57a46df2e105f39bc822f52fa670da5132b34
[jscl.git] / src / compiler.lisp
1 ;;; compiler.lisp --- 
2
3 ;; copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
6 ;; JSCL is free software: you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation, either version 3 of the
9 ;; License, or (at your option) any later version.
10 ;;
11 ;; JSCL is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;; General Public License for more details.
15 ;;
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;;;; Compiler
20
21 ;;; Translate the Lisp code to Javascript. It will compile the special
22 ;;; forms. Some primitive functions are compiled as special forms
23 ;;; too. The respective real functions are defined in the target (see
24 ;;; the beginning of this file) as well as some primitive functions.
25
26 (defun code (&rest args)
27   (mapconcat (lambda (arg)
28                (cond
29                  ((null arg) "")
30                  ((integerp arg) (integer-to-string arg))
31                  ((floatp arg) (float-to-string arg))
32                  ((stringp arg) arg)
33                  (t (error "Unknown argument `~S'." arg))))
34              args))
35
36 ;;; Wrap X with a Javascript code to convert the result from
37 ;;; Javascript generalized booleans to T or NIL.
38 (defun js!bool (x)
39   (code "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
40
41 ;;; Concatenate the arguments and wrap them with a self-calling
42 ;;; Javascript anonymous function. It is used to make some Javascript
43 ;;; statements valid expressions and provide a private scope as well.
44 ;;; It could be defined as function, but we could do some
45 ;;; preprocessing in the future.
46 (defmacro js!selfcall (&body body)
47   `(code "(function(){" *newline* (indent ,@body) "})()"))
48
49 ;;; Like CODE, but prefix each line with four spaces. Two versions
50 ;;; of this function are available, because the Ecmalisp version is
51 ;;; very slow and bootstraping was annoying.
52
53 #+jscl
54 (defun indent (&rest string)
55   (let ((input (apply #'code string)))
56     (let ((output "")
57           (index 0)
58           (size (length input)))
59       (when (plusp (length input)) (concatf output "    "))
60       (while (< index size)
61         (let ((str
62                (if (and (char= (char input index) #\newline)
63                         (< index (1- size))
64                         (not (char= (char input (1+ index)) #\newline)))
65                    (concat (string #\newline) "    ")
66                    (string (char input index)))))
67           (concatf output str))
68         (incf index))
69       output)))
70
71 #+common-lisp
72 (defun indent (&rest string)
73   (with-output-to-string (*standard-output*)
74     (with-input-from-string (input (apply #'code string))
75       (loop
76          for line = (read-line input nil)
77          while line
78          do (write-string "    ")
79          do (write-line line)))))
80
81
82 ;;; A Form can return a multiple values object calling VALUES, like
83 ;;; values(arg1, arg2, ...). It will work in any context, as well as
84 ;;; returning an individual object. However, if the special variable
85 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
86 ;;; value will be used, so we can optimize to avoid the VALUES
87 ;;; function call.
88 (defvar *multiple-value-p* nil)
89
90 ;;; Environment
91
92 (def!struct binding
93   name
94   type
95   value
96   declarations)
97
98 (def!struct lexenv
99   variable
100   function
101   block
102   gotag)
103
104 (defun lookup-in-lexenv (name lexenv namespace)
105   (find name (ecase namespace
106                 (variable (lexenv-variable lexenv))
107                 (function (lexenv-function lexenv))
108                 (block    (lexenv-block    lexenv))
109                 (gotag    (lexenv-gotag    lexenv)))
110         :key #'binding-name))
111
112 (defun push-to-lexenv (binding lexenv namespace)
113   (ecase namespace
114     (variable (push binding (lexenv-variable lexenv)))
115     (function (push binding (lexenv-function lexenv)))
116     (block    (push binding (lexenv-block    lexenv)))
117     (gotag    (push binding (lexenv-gotag    lexenv)))))
118
119 (defun extend-lexenv (bindings lexenv namespace)
120   (let ((env (copy-lexenv lexenv)))
121     (dolist (binding (reverse bindings) env)
122       (push-to-lexenv binding env namespace))))
123
124
125 (defvar *environment* (make-lexenv))
126
127 (defvar *variable-counter* 0)
128
129 (defun gvarname (symbol)
130   (declare (ignore symbol))
131   (code "v" (incf *variable-counter*)))
132
133 (defun translate-variable (symbol)
134   (awhen (lookup-in-lexenv symbol *environment* 'variable)
135     (binding-value it)))
136
137 (defun extend-local-env (args)
138   (let ((new (copy-lexenv *environment*)))
139     (dolist (symbol args new)
140       (let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
141         (push-to-lexenv b new 'variable)))))
142
143 ;;; Toplevel compilations
144 (defvar *toplevel-compilations* nil)
145
146 (defun toplevel-compilation (string)
147   (push string *toplevel-compilations*))
148
149 (defun null-or-empty-p (x)
150   (zerop (length x)))
151
152 (defun get-toplevel-compilations ()
153   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
154
155 (defun %compile-defmacro (name lambda)
156   (toplevel-compilation (ls-compile `',name))
157   (let ((binding (make-binding :name name :type 'macro :value lambda)))
158     (push-to-lexenv binding  *environment* 'function))
159   name)
160
161 (defun global-binding (name type namespace)
162   (or (lookup-in-lexenv name *environment* namespace)
163       (let ((b (make-binding :name name :type type :value nil)))
164         (push-to-lexenv b *environment* namespace)
165         b)))
166
167 (defun claimp (symbol namespace claim)
168   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
169     (and b (member claim (binding-declarations b)))))
170
171 (defun !proclaim (decl)
172   (case (car decl)
173     (special
174      (dolist (name (cdr decl))
175        (let ((b (global-binding name 'variable 'variable)))
176          (push 'special (binding-declarations b)))))
177     (notinline
178      (dolist (name (cdr decl))
179        (let ((b (global-binding name 'function 'function)))
180          (push 'notinline (binding-declarations b)))))
181     (constant
182      (dolist (name (cdr decl))
183        (let ((b (global-binding name 'variable 'variable)))
184          (push 'constant (binding-declarations b)))))))
185
186 #+jscl
187 (fset 'proclaim #'!proclaim)
188
189 (defun %define-symbol-macro (name expansion)
190   (let ((b (make-binding :name name :type 'macro :value expansion)))
191     (push-to-lexenv b *environment* 'variable)
192     name))
193
194 #+jscl
195 (defmacro define-symbol-macro (name expansion)
196   `(%define-symbol-macro ',name ',expansion))
197
198
199 ;;; Special forms
200
201 (defvar *compilations* nil)
202
203 (defmacro define-compilation (name args &body body)
204   ;; Creates a new primitive `name' with parameters args and
205   ;; @body. The body can access to the local environment through the
206   ;; variable *ENVIRONMENT*.
207   `(push (list ',name (lambda ,args (block ,name ,@body)))
208          *compilations*))
209
210 (define-compilation if (condition true false)
211   (code "(" (ls-compile condition) " !== " (ls-compile nil)
212         " ? " (ls-compile true *multiple-value-p*)
213         " : " (ls-compile false *multiple-value-p*)
214         ")"))
215
216 (defvar *ll-keywords* '(&optional &rest &key))
217
218 (defun list-until-keyword (list)
219   (if (or (null list) (member (car list) *ll-keywords*))
220       nil
221       (cons (car list) (list-until-keyword (cdr list)))))
222
223 (defun ll-section (keyword ll)
224   (list-until-keyword (cdr (member keyword ll))))
225
226 (defun ll-required-arguments (ll)
227   (list-until-keyword ll))
228
229 (defun ll-optional-arguments-canonical (ll)
230   (mapcar #'ensure-list (ll-section '&optional ll)))
231
232 (defun ll-optional-arguments (ll)
233   (mapcar #'car (ll-optional-arguments-canonical ll)))
234
235 (defun ll-rest-argument (ll)
236   (let ((rest (ll-section '&rest ll)))
237     (when (cdr rest)
238       (error "Bad lambda-list `~S'." ll))
239     (car rest)))
240
241 (defun ll-keyword-arguments-canonical (ll)
242   (flet ((canonicalize (keyarg)
243            ;; Build a canonical keyword argument descriptor, filling
244            ;; the optional fields. The result is a list of the form
245            ;; ((keyword-name var) init-form).
246            (let ((arg (ensure-list keyarg)))
247              (cons (if (listp (car arg))
248                        (car arg)
249                        (list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
250                    (cdr arg)))))
251     (mapcar #'canonicalize (ll-section '&key ll))))
252
253 (defun ll-keyword-arguments (ll)
254   (mapcar (lambda (keyarg) (second (first keyarg)))
255           (ll-keyword-arguments-canonical ll)))
256
257 (defun ll-svars (lambda-list)
258   (let ((args
259          (append
260           (ll-keyword-arguments-canonical lambda-list)
261           (ll-optional-arguments-canonical lambda-list))))
262     (remove nil (mapcar #'third args))))
263
264 (defun lambda-name/docstring-wrapper (name docstring &rest strs)
265   (if (or name docstring)
266       (js!selfcall
267         "var func = " (join strs) ";" *newline*
268         (when name
269           (code "func.fname = '" (escape-string name) "';" *newline*))
270         (when docstring
271           (code "func.docstring = '" (escape-string docstring) "';" *newline*))
272         "return func;" *newline*)
273       (apply #'code strs)))
274
275 (defun lambda-check-argument-count
276     (n-required-arguments n-optional-arguments rest-p)
277   ;; Note: Remember that we assume that the number of arguments of a
278   ;; call is at least 1 (the values argument).
279   (let ((min n-required-arguments)
280         (max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
281     (block nil
282       ;; Special case: a positive exact number of arguments.
283       (when (and (< 0 min) (eql min max))
284         (return (code "checkArgs(nargs, " min ");" *newline*)))
285       ;; General case:
286       (code
287        (when (< 0 min)
288          (code "checkArgsAtLeast(nargs, " min ");" *newline*))
289        (when (numberp max)
290          (code "checkArgsAtMost(nargs, " max ");" *newline*))))))
291
292 (defun compile-lambda-optional (ll)
293   (let* ((optional-arguments (ll-optional-arguments-canonical ll))
294          (n-required-arguments (length (ll-required-arguments ll)))
295          (n-optional-arguments (length optional-arguments)))
296     (when optional-arguments
297       (code "switch(nargs){" *newline*
298             (let ((cases nil)
299                   (idx 0))
300               (progn
301                 (while (< idx n-optional-arguments)
302                   (let ((arg (nth idx optional-arguments)))
303                     (push (code "case " (+ idx n-required-arguments) ":" *newline*
304                                 (indent (translate-variable (car arg))
305                                         "="
306                                         (ls-compile (cadr arg)) ";" *newline*)
307                                 (when (third arg)
308                                   (indent (translate-variable (third arg))
309                                           "="
310                                           (ls-compile nil)
311                                           ";" *newline*)))
312                           cases)
313                     (incf idx)))
314                 (push (code "default: break;" *newline*) cases)
315                 (join (reverse cases))))
316             "}" *newline*))))
317
318 (defun compile-lambda-rest (ll)
319   (let ((n-required-arguments (length (ll-required-arguments ll)))
320         (n-optional-arguments (length (ll-optional-arguments ll)))
321         (rest-argument (ll-rest-argument ll)))
322     (when rest-argument
323       (let ((js!rest (translate-variable rest-argument)))
324         (code "var " js!rest "= " (ls-compile nil) ";" *newline*
325               "for (var i = nargs-1; i>=" (+ n-required-arguments n-optional-arguments)
326               "; i--)" *newline*
327               (indent js!rest " = {car: arguments[i+2], cdr: " js!rest "};" *newline*))))))
328
329 (defun compile-lambda-parse-keywords (ll)
330   (let ((n-required-arguments
331          (length (ll-required-arguments ll)))
332         (n-optional-arguments
333          (length (ll-optional-arguments ll)))
334         (keyword-arguments
335          (ll-keyword-arguments-canonical ll)))
336     (code
337      ;; Declare variables
338      (mapconcat (lambda (arg)
339                   (let ((var (second (car arg))))
340                     (code "var " (translate-variable var) "; " *newline*
341                           (when (third arg)
342                             (code "var " (translate-variable (third arg))
343                                   " = " (ls-compile nil)
344                                   ";" *newline*)))))
345                 keyword-arguments)
346      ;; Parse keywords
347      (flet ((parse-keyword (keyarg)
348               ;; ((keyword-name var) init-form)
349               (code "for (i=" (+ n-required-arguments n-optional-arguments)
350                     "; i<nargs; i+=2){" *newline*
351                     (indent
352                      "if (arguments[i+2] === " (ls-compile (caar keyarg)) "){" *newline*
353                      (indent (translate-variable (cadr (car keyarg)))
354                              " = arguments[i+3];"
355                              *newline*
356                              (let ((svar (third keyarg)))
357                                (when svar
358                                  (code (translate-variable svar) " = " (ls-compile t) ";" *newline*)))
359                              "break;" *newline*)
360                      "}" *newline*)
361                     "}" *newline*
362                     ;; Default value
363                     "if (i == nargs){" *newline*
364                     (indent (translate-variable (cadr (car keyarg))) " = " (ls-compile (cadr keyarg)) ";" *newline*)
365                     "}" *newline*)))
366        (when keyword-arguments
367          (code "var i;" *newline*
368                (mapconcat #'parse-keyword keyword-arguments))))
369      ;; Check for unknown keywords
370      (when keyword-arguments
371        (code "for (i=" (+ n-required-arguments n-optional-arguments)
372              "; i<nargs; i+=2){" *newline*
373              (indent "if ("
374                      (join (mapcar (lambda (x)
375                                      (concat "arguments[i+2] !== " (ls-compile (caar x))))
376                                    keyword-arguments)
377                            " && ")
378                      ")" *newline*
379                      (indent
380                       "throw 'Unknown keyword argument ' + xstring(arguments[i].name);" *newline*))
381              "}" *newline*)))))
382
383 (defun parse-lambda-list (ll)
384   (values (ll-required-arguments ll)
385           (ll-optional-arguments ll)
386           (ll-keyword-arguments  ll)
387           (ll-rest-argument      ll)))
388
389 ;;; Process BODY for declarations and/or docstrings. Return as
390 ;;; multiple values the BODY without docstrings or declarations, the
391 ;;; list of declaration forms and the docstring.
392 (defun parse-body (body &key declarations docstring)
393   (let ((value-declarations)
394         (value-docstring))
395     ;; Parse declarations
396     (when declarations
397       (do* ((rest body (cdr rest))
398             (form (car rest) (car rest)))
399            ((or (atom form) (not (eq (car form) 'declare)))
400             (setf body rest))
401         (push form value-declarations)))
402     ;; Parse docstring
403     (when (and docstring
404                (stringp (car body))
405                (not (null (cdr body))))
406       (setq value-docstring (car body))
407       (setq body (cdr body)))
408     (values body value-declarations value-docstring)))
409
410 ;;; Compile a lambda function with lambda list LL and body BODY. If
411 ;;; NAME is given, it should be a constant string and it will become
412 ;;; the name of the function. If BLOCK is non-NIL, a named block is
413 ;;; created around the body. NOTE: No block (even anonymous) is
414 ;;; created if BLOCk is NIL.
415 (defun compile-lambda (ll body &key name block)
416   (multiple-value-bind (required-arguments
417                         optional-arguments
418                         keyword-arguments
419                         rest-argument)
420       (parse-lambda-list ll)
421     (multiple-value-bind (body decls documentation)
422         (parse-body body :declarations t :docstring t)
423       (declare (ignore decls))
424       (let ((n-required-arguments (length required-arguments))
425             (n-optional-arguments (length optional-arguments))
426             (*environment* (extend-local-env
427                             (append (ensure-list rest-argument)
428                                     required-arguments
429                                     optional-arguments
430                                     keyword-arguments
431                                     (ll-svars ll)))))
432         (lambda-name/docstring-wrapper name documentation
433          "(function ("
434          (join (list* "values"
435                       "nargs"
436                       (mapcar #'translate-variable
437                               (append required-arguments optional-arguments)))
438                ",")
439          "){" *newline*
440          (indent
441           ;; Check number of arguments
442           (lambda-check-argument-count n-required-arguments
443                                        n-optional-arguments
444                                        (or rest-argument keyword-arguments))
445                                         (compile-lambda-optional ll)
446                                         (compile-lambda-rest ll)
447                                         (compile-lambda-parse-keywords ll)
448                                         (let ((*multiple-value-p* t))
449                                           (if block
450                                               (ls-compile-block `((block ,block ,@body)) t)
451                                               (ls-compile-block body t))))
452          "})")))))
453
454
455 (defun setq-pair (var val)
456   (let ((b (lookup-in-lexenv var *environment* 'variable)))
457     (cond
458       ((and b
459             (eq (binding-type b) 'variable)
460             (not (member 'special (binding-declarations b)))
461             (not (member 'constant (binding-declarations b))))
462        (code (binding-value b) " = " (ls-compile val)))
463       ((and b (eq (binding-type b) 'macro))
464        (ls-compile `(setf ,var ,val)))
465       (t
466        (ls-compile `(set ',var ,val))))))
467
468
469 (define-compilation setq (&rest pairs)
470   (let ((result ""))
471     (while t
472       (cond
473         ((null pairs) (return))
474         ((null (cdr pairs))
475          (error "Odd pairs in SETQ"))
476         (t
477          (concatf result
478            (concat (setq-pair (car pairs) (cadr pairs))
479                    (if (null (cddr pairs)) "" ", ")))
480          (setq pairs (cddr pairs)))))
481     (code "(" result ")")))
482
483
484 ;;; Compilation of literals an object dumping
485
486 (defun escape-string (string)
487   (let ((output "")
488         (index 0)
489         (size (length string)))
490     (while (< index size)
491       (let ((ch (char string index)))
492         (when (or (char= ch #\") (char= ch #\\))
493           (setq output (concat output "\\")))
494         (when (or (char= ch #\newline))
495           (setq output (concat output "\\"))
496           (setq ch #\n))
497         (setq output (concat output (string ch))))
498       (incf index))
499     output))
500
501 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
502 ;;; the bootstrap. Once everything is compiled, we want to dump the
503 ;;; whole global environment to the output file to reproduce it in the
504 ;;; run-time. However, the environment must contain expander functions
505 ;;; rather than lists. We do not know how to dump function objects
506 ;;; itself, so we mark the list definitions with this object and the
507 ;;; compiler will be called when this object has to be dumped.
508 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
509 ;;;
510 ;;; Indeed, perhaps to compile the object other macros need to be
511 ;;; evaluated. For this reason we define a valid macro-function for
512 ;;; this symbol.
513 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
514 #+common-lisp
515 (setf (macro-function *magic-unquote-marker*)
516       (lambda (form &optional environment)
517         (declare (ignore environment))
518         (second form)))
519
520 (defvar *literal-table* nil)
521 (defvar *literal-counter* 0)
522
523 (defun genlit ()
524   (code "l" (incf *literal-counter*)))
525
526 (defun dump-symbol (symbol)
527   #+common-lisp
528   (let ((package (symbol-package symbol)))
529     (if (eq package (find-package "KEYWORD"))
530         (code "(new Symbol(" (dump-string (symbol-name symbol)) ", " (dump-string (package-name package)) "))")
531         (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")))
532   #+jscl
533   (let ((package (symbol-package symbol)))
534     (if (null package)
535         (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")
536         (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
537
538 (defun dump-cons (cons)
539   (let ((head (butlast cons))
540         (tail (last cons)))
541     (code "QIList("
542           (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
543           (literal (car tail) t)
544           ","
545           (literal (cdr tail) t)
546           ")")))
547
548 (defun dump-array (array)
549   (let ((elements (vector-to-list array)))
550     (concat "[" (join (mapcar #'literal elements) ", ") "]")))
551
552 (defun dump-string (string)
553   (code "make_lisp_string(\"" (escape-string string) "\")"))
554
555 (defun literal (sexp &optional recursive)
556   (cond
557     ((integerp sexp) (integer-to-string sexp))
558     ((floatp sexp) (float-to-string sexp))
559     ((characterp sexp) (code "\"" (escape-string (string sexp)) "\""))
560     (t
561      (or (cdr (assoc sexp *literal-table* :test #'equal))
562          (let ((dumped (typecase sexp
563                          (symbol (dump-symbol sexp))
564                          (string (dump-string sexp))
565                          (cons
566                           ;; BOOTSTRAP MAGIC: See the root file
567                           ;; jscl.lisp and the function
568                           ;; `dump-global-environment' for futher
569                           ;; information.
570                           (if (eq (car sexp) *magic-unquote-marker*)
571                               (ls-compile (second sexp))
572                               (dump-cons sexp)))
573                          (array (dump-array sexp)))))
574            (if (and recursive (not (symbolp sexp)))
575                dumped
576                (let ((jsvar (genlit)))
577                  (push (cons sexp jsvar) *literal-table*)
578                  (toplevel-compilation (code "var " jsvar " = " dumped))
579                  (when (keywordp sexp)
580                    (toplevel-compilation (code jsvar ".value = " jsvar)))
581                  jsvar)))))))
582
583
584 (define-compilation quote (sexp)
585   (literal sexp))
586
587 (define-compilation %while (pred &rest body)
588   (js!selfcall
589     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
590     (indent (ls-compile-block body))
591     "}"
592     "return " (ls-compile nil) ";" *newline*))
593
594 (define-compilation function (x)
595   (cond
596     ((and (listp x) (eq (car x) 'lambda))
597      (compile-lambda (cadr x) (cddr x)))
598     ((and (listp x) (eq (car x) 'named-lambda))
599      ;; TODO: destructuring-bind now! Do error checking manually is
600      ;; very annoying.
601      (let ((name (cadr x))
602            (ll (caddr x))
603            (body (cdddr x)))
604        (compile-lambda ll body
605                        :name (symbol-name name)
606                        :block name)))
607     ((symbolp x)
608      (let ((b (lookup-in-lexenv x *environment* 'function)))
609        (if b
610            (binding-value b)
611            (ls-compile `(symbol-function ',x)))))))
612
613
614 (defun make-function-binding (fname)
615   (make-binding :name fname :type 'function :value (gvarname fname)))
616
617 (defun compile-function-definition (list)
618   (compile-lambda (car list) (cdr list)))
619
620 (defun translate-function (name)
621   (let ((b (lookup-in-lexenv name *environment* 'function)))
622     (and b (binding-value b))))
623
624 (define-compilation flet (definitions &rest body)
625   (let* ((fnames (mapcar #'car definitions))
626          (cfuncs (mapcar (lambda (def)
627                            (compile-lambda (cadr def)
628                                            `((block ,(car def)
629                                                ,@(cddr def)))))
630                          definitions))
631          (*environment*
632           (extend-lexenv (mapcar #'make-function-binding fnames)
633                          *environment*
634                          'function)))
635     (code "(function("
636           (join (mapcar #'translate-function fnames) ",")
637           "){" *newline*
638           (let ((body (ls-compile-block body t)))
639             (indent body))
640           "})(" (join cfuncs ",") ")")))
641
642 (define-compilation labels (definitions &rest body)
643   (let* ((fnames (mapcar #'car definitions))
644          (*environment*
645           (extend-lexenv (mapcar #'make-function-binding fnames)
646                          *environment*
647                          'function)))
648     (js!selfcall
649       (mapconcat (lambda (func)
650                    (code "var " (translate-function (car func))
651                          " = " (compile-lambda (cadr func)
652                                                `((block ,(car func) ,@(cddr func))))
653                          ";" *newline*))
654                  definitions)
655       (ls-compile-block body t))))
656
657
658 (defvar *compiling-file* nil)
659 (define-compilation eval-when-compile (&rest body)
660   (if *compiling-file*
661       (progn
662         (eval (cons 'progn body))
663         nil)
664       (ls-compile `(progn ,@body))))
665
666 (defmacro define-transformation (name args form)
667   `(define-compilation ,name ,args
668      (ls-compile ,form)))
669
670 (define-compilation progn (&rest body)
671   (if (null (cdr body))
672       (ls-compile (car body) *multiple-value-p*)
673       (js!selfcall (ls-compile-block body t))))
674
675 (defun special-variable-p (x)
676   (and (claimp x 'variable 'special) t))
677
678 ;;; Wrap CODE to restore the symbol values of the dynamic
679 ;;; bindings. BINDINGS is a list of pairs of the form
680 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
681 ;;; name to initialize the symbol value and where to stored
682 ;;; the old value.
683 (defun let-binding-wrapper (bindings body)
684   (when (null bindings)
685     (return-from let-binding-wrapper body))
686   (code
687    "try {" *newline*
688    (indent "var tmp;" *newline*
689            (mapconcat
690             (lambda (b)
691               (let ((s (ls-compile `(quote ,(car b)))))
692                 (code "tmp = " s ".value;" *newline*
693                       s ".value = " (cdr b) ";" *newline*
694                       (cdr b) " = tmp;" *newline*)))
695             bindings)
696            body *newline*)
697    "}" *newline*
698    "finally {"  *newline*
699    (indent
700     (mapconcat (lambda (b)
701                  (let ((s (ls-compile `(quote ,(car b)))))
702                    (code s ".value" " = " (cdr b) ";" *newline*)))
703                bindings))
704    "}" *newline*))
705
706 (define-compilation let (bindings &rest body)
707   (let* ((bindings (mapcar #'ensure-list bindings))
708          (variables (mapcar #'first bindings))
709          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
710          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
711          (dynamic-bindings))
712     (code "(function("
713           (join (mapcar (lambda (x)
714                           (if (special-variable-p x)
715                               (let ((v (gvarname x)))
716                                 (push (cons x v) dynamic-bindings)
717                                 v)
718                               (translate-variable x)))
719                         variables)
720                 ",")
721           "){" *newline*
722           (let ((body (ls-compile-block body t)))
723             (indent (let-binding-wrapper dynamic-bindings body)))
724           "})(" (join cvalues ",") ")")))
725
726
727 ;;; Return the code to initialize BINDING, and push it extending the
728 ;;; current lexical environment if the variable is not special.
729 (defun let*-initialize-value (binding)
730   (let ((var (first binding))
731         (value (second binding)))
732     (if (special-variable-p var)
733         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
734         (let* ((v (gvarname var))
735                (b (make-binding :name var :type 'variable :value v)))
736           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
737             (push-to-lexenv b *environment* 'variable))))))
738
739 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
740 ;;; DOES NOT generate code to initialize the value of the symbols,
741 ;;; unlike let-binding-wrapper.
742 (defun let*-binding-wrapper (symbols body)
743   (when (null symbols)
744     (return-from let*-binding-wrapper body))
745   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
746                        (remove-if-not #'special-variable-p symbols))))
747     (code
748      "try {" *newline*
749      (indent
750       (mapconcat (lambda (b)
751                    (let ((s (ls-compile `(quote ,(car b)))))
752                      (code "var " (cdr b) " = " s ".value;" *newline*)))
753                  store)
754       body)
755      "}" *newline*
756      "finally {" *newline*
757      (indent
758       (mapconcat (lambda (b)
759                    (let ((s (ls-compile `(quote ,(car b)))))
760                      (code s ".value" " = " (cdr b) ";" *newline*)))
761                  store))
762      "}" *newline*)))
763
764 (define-compilation let* (bindings &rest body)
765   (let ((bindings (mapcar #'ensure-list bindings))
766         (*environment* (copy-lexenv *environment*)))
767     (js!selfcall
768       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
769             (body (concat (mapconcat #'let*-initialize-value bindings)
770                           (ls-compile-block body t))))
771         (let*-binding-wrapper specials body)))))
772
773
774 (define-compilation block (name &rest body)
775   ;; We use Javascript exceptions to implement non local control
776   ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
777   ;; generated object to identify the block. The instance of a empty
778   ;; array is used to distinguish between nested dynamic Javascript
779   ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
780   ;; futher details.
781   (let* ((idvar (gvarname name))
782          (b (make-binding :name name :type 'block :value idvar)))
783     (when *multiple-value-p*
784       (push 'multiple-value (binding-declarations b)))
785     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
786            (cbody (ls-compile-block body t)))
787       (if (member 'used (binding-declarations b))
788           (js!selfcall
789             "try {" *newline*
790             "var " idvar " = [];" *newline*
791             (indent cbody)
792             "}" *newline*
793             "catch (cf){" *newline*
794             "    if (cf.type == 'block' && cf.id == " idvar ")" *newline*
795             (if *multiple-value-p*
796                 "        return values.apply(this, forcemv(cf.values));"
797                 "        return cf.values;")
798             *newline*
799             "    else" *newline*
800             "        throw cf;" *newline*
801             "}" *newline*)
802           (js!selfcall cbody)))))
803
804 (define-compilation return-from (name &optional value)
805   (let* ((b (lookup-in-lexenv name *environment* 'block))
806          (multiple-value-p (member 'multiple-value (binding-declarations b))))
807     (when (null b)
808       (error "Return from unknown block `~S'." (symbol-name name)))
809     (push 'used (binding-declarations b))
810     ;; The binding value is the name of a variable, whose value is the
811     ;; unique identifier of the block as exception. We can't use the
812     ;; variable name itself, because it could not to be unique, so we
813     ;; capture it in a closure.
814     (js!selfcall
815       (when multiple-value-p (code "var values = mv;" *newline*))
816       "throw ({"
817       "type: 'block', "
818       "id: " (binding-value b) ", "
819       "values: " (ls-compile value multiple-value-p) ", "
820       "message: 'Return from unknown block " (symbol-name name) ".'"
821       "})")))
822
823 (define-compilation catch (id &rest body)
824   (js!selfcall
825     "var id = " (ls-compile id) ";" *newline*
826     "try {" *newline*
827     (indent (ls-compile-block body t)) *newline*
828     "}" *newline*
829     "catch (cf){" *newline*
830     "    if (cf.type == 'catch' && cf.id == id)" *newline*
831     (if *multiple-value-p*
832         "        return values.apply(this, forcemv(cf.values));"
833         "        return pv.apply(this, forcemv(cf.values));")
834     *newline*
835     "    else" *newline*
836     "        throw cf;" *newline*
837     "}" *newline*))
838
839 (define-compilation throw (id value)
840   (js!selfcall
841     "var values = mv;" *newline*
842     "throw ({"
843     "type: 'catch', "
844     "id: " (ls-compile id) ", "
845     "values: " (ls-compile value t) ", "
846     "message: 'Throw uncatched.'"
847     "})"))
848
849 (defun go-tag-p (x)
850   (or (integerp x) (symbolp x)))
851
852 (defun declare-tagbody-tags (tbidx body)
853   (let* ((go-tag-counter 0)
854          (bindings
855           (mapcar (lambda (label)
856                     (let ((tagidx (integer-to-string (incf go-tag-counter))))
857                       (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
858                   (remove-if-not #'go-tag-p body))))
859     (extend-lexenv bindings *environment* 'gotag)))
860
861 (define-compilation tagbody (&rest body)
862   ;; Ignore the tagbody if it does not contain any go-tag. We do this
863   ;; because 1) it is easy and 2) many built-in forms expand to a
864   ;; implicit tagbody, so we save some space.
865   (unless (some #'go-tag-p body)
866     (return-from tagbody (ls-compile `(progn ,@body nil))))
867   ;; The translation assumes the first form in BODY is a label
868   (unless (go-tag-p (car body))
869     (push (gensym "START") body))
870   ;; Tagbody compilation
871   (let ((branch (gvarname 'branch))
872         (tbidx (gvarname 'tbidx)))
873     (let ((*environment* (declare-tagbody-tags tbidx body))
874           initag)
875       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
876         (setq initag (second (binding-value b))))
877       (js!selfcall
878         ;; TAGBODY branch to take
879         "var " branch " = " initag ";" *newline*
880         "var " tbidx " = [];" *newline*
881         "tbloop:" *newline*
882         "while (true) {" *newline*
883         (indent "try {" *newline*
884                 (indent (let ((content ""))
885                           (code "switch(" branch "){" *newline*
886                                 "case " initag ":" *newline*
887                                 (dolist (form (cdr body) content)
888                                   (concatf content
889                                     (if (not (go-tag-p form))
890                                         (indent (ls-compile form) ";" *newline*)
891                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
892                                           (code "case " (second (binding-value b)) ":" *newline*)))))
893                                 "default:" *newline*
894                                 "    break tbloop;" *newline*
895                                 "}" *newline*)))
896                 "}" *newline*
897                 "catch (jump) {" *newline*
898                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
899                 "        " branch " = jump.label;" *newline*
900                 "    else" *newline*
901                 "        throw(jump);" *newline*
902                 "}" *newline*)
903         "}" *newline*
904         "return " (ls-compile nil) ";" *newline*))))
905
906 (define-compilation go (label)
907   (let ((b (lookup-in-lexenv label *environment* 'gotag))
908         (n (cond
909              ((symbolp label) (symbol-name label))
910              ((integerp label) (integer-to-string label)))))
911     (when (null b)
912       (error "Unknown tag `~S'" label))
913     (js!selfcall
914       "throw ({"
915       "type: 'tagbody', "
916       "id: " (first (binding-value b)) ", "
917       "label: " (second (binding-value b)) ", "
918       "message: 'Attempt to GO to non-existing tag " n "'"
919       "})" *newline*)))
920
921 (define-compilation unwind-protect (form &rest clean-up)
922   (js!selfcall
923     "var ret = " (ls-compile nil) ";" *newline*
924     "try {" *newline*
925     (indent "ret = " (ls-compile form) ";" *newline*)
926     "} finally {" *newline*
927     (indent (ls-compile-block clean-up))
928     "}" *newline*
929     "return ret;" *newline*))
930
931 (define-compilation multiple-value-call (func-form &rest forms)
932   (js!selfcall
933     "var func = " (ls-compile func-form) ";" *newline*
934     "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
935     "return "
936     (js!selfcall
937       "var values = mv;" *newline*
938       "var vs;" *newline*
939       (mapconcat (lambda (form)
940                    (code "vs = " (ls-compile form t) ";" *newline*
941                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
942                          (indent "args = args.concat(vs);" *newline*)
943                          "else" *newline*
944                          (indent "args.push(vs);" *newline*)))
945                  forms)
946       "args[1] = args.length-2;" *newline*
947       "return func.apply(window, args);" *newline*) ";" *newline*))
948
949 (define-compilation multiple-value-prog1 (first-form &rest forms)
950   (js!selfcall
951     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
952     (ls-compile-block forms)
953     "return args;" *newline*))
954
955
956 ;;; Backquote implementation.
957 ;;;
958 ;;;    Author: Guy L. Steele Jr.     Date: 27 December 1985
959 ;;;    Tested under Symbolics Common Lisp and Lucid Common Lisp.
960 ;;;    This software is in the public domain.
961
962 ;;;    The following are unique tokens used during processing.
963 ;;;    They need not be symbols; they need not even be atoms.
964 (defvar *comma* 'unquote)
965 (defvar *comma-atsign* 'unquote-splicing)
966
967 (defvar *bq-list* (make-symbol "BQ-LIST"))
968 (defvar *bq-append* (make-symbol "BQ-APPEND"))
969 (defvar *bq-list** (make-symbol "BQ-LIST*"))
970 (defvar *bq-nconc* (make-symbol "BQ-NCONC"))
971 (defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
972 (defvar *bq-quote* (make-symbol "BQ-QUOTE"))
973 (defvar *bq-quote-nil* (list *bq-quote* nil))
974
975 ;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
976 ;;; the expression foo, looking for occurrences of #:COMMA,
977 ;;; #:COMMA-ATSIGN, and #:COMMA-DOT.  It constructs code in strict
978 ;;; accordance with the rules on pages 349-350 of the first edition
979 ;;; (pages 528-529 of this second edition).  It then optionally
980 ;;; applies a code simplifier.
981
982 ;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
983 ;;; processing applies the code simplifier.  If the value is NIL,
984 ;;; then the code resulting from BACKQUOTE is exactly that
985 ;;; specified by the official rules.
986 (defparameter *bq-simplify* t)
987
988 (defmacro backquote (x)
989   (bq-completely-process x))
990
991 ;;; Backquote processing proceeds in three stages:
992 ;;;
993 ;;; (1) BQ-PROCESS applies the rules to remove occurrences of
994 ;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
995 ;;; this level of BACKQUOTE.  (It also causes embedded calls to
996 ;;; BACKQUOTE to be expanded so that nesting is properly handled.)
997 ;;; Code is produced that is expressed in terms of functions
998 ;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE.  This is done
999 ;;; so that the simplifier will simplify only list construction
1000 ;;; functions actually generated by BACKQUOTE and will not involve
1001 ;;; any user code in the simplification.  #:BQ-LIST means LIST,
1002 ;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
1003 ;;; but indicates places where "%." was used and where NCONC may
1004 ;;; therefore be introduced by the simplifier for efficiency.
1005 ;;;
1006 ;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
1007 ;;; BQ-PROCESS to produce equivalent but faster code.  The
1008 ;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
1009 ;;; introduced into the code.
1010 ;;;
1011 ;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
1012 ;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
1013 ;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
1014 ;;; replaced by its argument).  #:BQ-LIST* is replaced by either
1015 ;;; LIST* or CONS (the latter is used in the two-argument case,
1016 ;;; purely to make the resulting code a tad more readable).
1017
1018 (defun bq-completely-process (x)
1019   (let ((raw-result (bq-process x)))
1020     (bq-remove-tokens (if *bq-simplify*
1021                           (bq-simplify raw-result)
1022                           raw-result))))
1023
1024 (defun bq-process (x)
1025   (cond ((atom x)
1026          (list *bq-quote* x))
1027         ((eq (car x) 'backquote)
1028          (bq-process (bq-completely-process (cadr x))))
1029         ((eq (car x) *comma*) (cadr x))
1030         ((eq (car x) *comma-atsign*)
1031          (error ",@~S after `" (cadr x)))
1032         ;; ((eq (car x) *comma-dot*)
1033         ;;  ;; (error ",.~S after `" (cadr x))
1034         ;;  (error "ill-formed"))
1035         (t (do ((p x (cdr p))
1036                 (q '() (cons (bracket (car p)) q)))
1037                ((atom p)
1038                 (cons *bq-append*
1039                       (nreconc q (list (list *bq-quote* p)))))
1040              (when (eq (car p) *comma*)
1041                (unless (null (cddr p))
1042                  (error "Malformed ,~S" p))
1043                (return (cons *bq-append*
1044                              (nreconc q (list (cadr p))))))
1045              (when (eq (car p) *comma-atsign*)
1046                (error "Dotted ,@~S" p))
1047              ;; (when (eq (car p) *comma-dot*)
1048              ;;   ;; (error "Dotted ,.~S" p)
1049              ;;   (error "Dotted"))
1050              ))))
1051
1052 ;;; This implements the bracket operator of the formal rules.
1053 (defun bracket (x)
1054   (cond ((atom x)
1055          (list *bq-list* (bq-process x)))
1056         ((eq (car x) *comma*)
1057          (list *bq-list* (cadr x)))
1058         ((eq (car x) *comma-atsign*)
1059          (cadr x))
1060         ;; ((eq (car x) *comma-dot*)
1061         ;;  (list *bq-clobberable* (cadr x)))
1062         (t (list *bq-list* (bq-process x)))))
1063
1064 ;;; This auxiliary function is like MAPCAR but has two extra
1065 ;;; purposes: (1) it handles dotted lists; (2) it tries to make
1066 ;;; the result share with the argument x as much as possible.
1067 (defun maptree (fn x)
1068   (if (atom x)
1069       (funcall fn x)
1070       (let ((a (funcall fn (car x)))
1071             (d (maptree fn (cdr x))))
1072         (if (and (eql a (car x)) (eql d (cdr x)))
1073             x
1074             (cons a d)))))
1075
1076 ;;; This predicate is true of a form that when read looked
1077 ;;; like %@foo or %.foo.
1078 (defun bq-splicing-frob (x)
1079   (and (consp x)
1080        (or (eq (car x) *comma-atsign*)
1081            ;; (eq (car x) *comma-dot*)
1082            )))
1083
1084 ;;; This predicate is true of a form that when read
1085 ;;; looked like %@foo or %.foo or just plain %foo.
1086 (defun bq-frob (x)
1087   (and (consp x)
1088        (or (eq (car x) *comma*)
1089            (eq (car x) *comma-atsign*)
1090            ;; (eq (car x) *comma-dot*)
1091            )))
1092
1093 ;;; The simplifier essentially looks for calls to #:BQ-APPEND and
1094 ;;; tries to simplify them.  The arguments to #:BQ-APPEND are
1095 ;;; processed from right to left, building up a replacement form.
1096 ;;; At each step a number of special cases are handled that,
1097 ;;; loosely speaking, look like this:
1098 ;;;
1099 ;;;  (APPEND (LIST a b c) foo) => (LIST* a b c foo)
1100 ;;;       provided a, b, c are not splicing frobs
1101 ;;;  (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
1102 ;;;       provided a, b, c are not splicing frobs
1103 ;;;  (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
1104 ;;;  (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
1105 (defun bq-simplify (x)
1106   (if (atom x)
1107       x
1108       (let ((x (if (eq (car x) *bq-quote*)
1109                    x
1110                    (maptree #'bq-simplify x))))
1111         (if (not (eq (car x) *bq-append*))
1112             x
1113             (bq-simplify-args x)))))
1114
1115 (defun bq-simplify-args (x)
1116   (do ((args (reverse (cdr x)) (cdr args))
1117        (result
1118          nil
1119          (cond ((atom (car args))
1120                 (bq-attach-append *bq-append* (car args) result))
1121                ((and (eq (caar args) *bq-list*)
1122                      (notany #'bq-splicing-frob (cdar args)))
1123                 (bq-attach-conses (cdar args) result))
1124                ((and (eq (caar args) *bq-list**)
1125                      (notany #'bq-splicing-frob (cdar args)))
1126                 (bq-attach-conses
1127                   (reverse (cdr (reverse (cdar args))))
1128                   (bq-attach-append *bq-append*
1129                                     (car (last (car args)))
1130                                     result)))
1131                ((and (eq (caar args) *bq-quote*)
1132                      (consp (cadar args))
1133                      (not (bq-frob (cadar args)))
1134                      (null (cddar args)))
1135                 (bq-attach-conses (list (list *bq-quote*
1136                                               (caadar args)))
1137                                   result))
1138                ((eq (caar args) *bq-clobberable*)
1139                 (bq-attach-append *bq-nconc* (cadar args) result))
1140                (t (bq-attach-append *bq-append*
1141                                     (car args)
1142                                     result)))))
1143       ((null args) result)))
1144
1145 (defun null-or-quoted (x)
1146   (or (null x) (and (consp x) (eq (car x) *bq-quote*))))
1147
1148 ;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
1149 ;;; or #:BQ-NCONC.  This produces a form (op item result) but
1150 ;;; some simplifications are done on the fly:
1151 ;;;
1152 ;;;  (op '(a b c) '(d e f g)) => '(a b c d e f g)
1153 ;;;  (op item 'nil) => item, provided item is not a splicable frob
1154 ;;;  (op item 'nil) => (op item), if item is a splicable frob
1155 ;;;  (op item (op a b c)) => (op item a b c)
1156 (defun bq-attach-append (op item result)
1157   (cond ((and (null-or-quoted item) (null-or-quoted result))
1158          (list *bq-quote* (append (cadr item) (cadr result))))
1159         ((or (null result) (equal result *bq-quote-nil*))
1160          (if (bq-splicing-frob item) (list op item) item))
1161         ((and (consp result) (eq (car result) op))
1162          (list* (car result) item (cdr result)))
1163         (t (list op item result))))
1164
1165 ;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
1166 ;;; `(LIST* ,@items ,result) but some simplifications are done
1167 ;;; on the fly.
1168 ;;;
1169 ;;;  (LIST* 'a 'b 'c 'd) => '(a b c . d)
1170 ;;;  (LIST* a b c 'nil) => (LIST a b c)
1171 ;;;  (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
1172 ;;;  (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
1173 (defun bq-attach-conses (items result)
1174   (cond ((and (every #'null-or-quoted items)
1175               (null-or-quoted result))
1176          (list *bq-quote*
1177                (append (mapcar #'cadr items) (cadr result))))
1178         ((or (null result) (equal result *bq-quote-nil*))
1179          (cons *bq-list* items))
1180         ((and (consp result)
1181               (or (eq (car result) *bq-list*)
1182                   (eq (car result) *bq-list**)))
1183          (cons (car result) (append items (cdr result))))
1184         (t (cons *bq-list** (append items (list result))))))
1185
1186 ;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
1187 ;;; (CONS a b) instead of (LIST* a b), purely for readability.
1188 (defun bq-remove-tokens (x)
1189   (cond ((eq x *bq-list*) 'list)
1190         ((eq x *bq-append*) 'append)
1191         ((eq x *bq-nconc*) 'nconc)
1192         ((eq x *bq-list**) 'list*)
1193         ((eq x *bq-quote*) 'quote)
1194         ((atom x) x)
1195         ((eq (car x) *bq-clobberable*)
1196          (bq-remove-tokens (cadr x)))
1197         ((and (eq (car x) *bq-list**)
1198               (consp (cddr x))
1199               (null (cdddr x)))
1200          (cons 'cons (maptree #'bq-remove-tokens (cdr x))))
1201         (t (maptree #'bq-remove-tokens x))))
1202
1203 (define-transformation backquote (form)
1204   (bq-completely-process form))
1205
1206
1207 ;;; Primitives
1208
1209 (defvar *builtins* nil)
1210
1211 (defmacro define-raw-builtin (name args &body body)
1212   ;; Creates a new primitive function `name' with parameters args and
1213   ;; @body. The body can access to the local environment through the
1214   ;; variable *ENVIRONMENT*.
1215   `(push (list ',name (lambda ,args (block ,name ,@body)))
1216          *builtins*))
1217
1218 (defmacro define-builtin (name args &body body)
1219   `(define-raw-builtin ,name ,args
1220      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1221        ,@body)))
1222
1223 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1224 (defmacro type-check (decls &body body)
1225   `(js!selfcall
1226      ,@(mapcar (lambda (decl)
1227                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1228                decls)
1229      ,@(mapcar (lambda (decl)
1230                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1231                         (indent "throw 'The value ' + "
1232                                 ,(first decl)
1233                                 " + ' is not a type "
1234                                 ,(second decl)
1235                                 ".';"
1236                                 *newline*)))
1237                decls)
1238      (code "return " (progn ,@body) ";" *newline*)))
1239
1240 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1241 ;;; a variable which holds a list of forms. It will compile them and
1242 ;;; store the result in some Javascript variables. BODY is evaluated
1243 ;;; with ARGS bound to the list of these variables to generate the
1244 ;;; code which performs the transformation on these variables.
1245
1246 (defun variable-arity-call (args function)
1247   (unless (consp args)
1248     (error "ARGS must be a non-empty list"))
1249   (let ((counter 0)
1250         (fargs '())
1251         (prelude ""))
1252     (dolist (x args)
1253       (cond
1254         ((floatp x) (push (float-to-string x) fargs))
1255         ((numberp x) (push (integer-to-string x) fargs))
1256         (t (let ((v (code "x" (incf counter))))
1257              (push v fargs)
1258              (concatf prelude
1259                (code "var " v " = " (ls-compile x) ";" *newline*
1260                      "if (typeof " v " !== 'number') throw 'Not a number!';"
1261                      *newline*))))))
1262     (js!selfcall prelude (funcall function (reverse fargs)))))
1263
1264
1265 (defmacro variable-arity (args &body body)
1266   (unless (symbolp args)
1267     (error "`~S' is not a symbol." args))
1268   `(variable-arity-call ,args
1269                         (lambda (,args)
1270                           (code "return " ,@body ";" *newline*))))
1271
1272 (defun num-op-num (x op y)
1273   (type-check (("x" "number" x) ("y" "number" y))
1274     (code "x" op "y")))
1275
1276 (define-raw-builtin + (&rest numbers)
1277   (if (null numbers)
1278       "0"
1279       (variable-arity numbers
1280         (join numbers "+"))))
1281
1282 (define-raw-builtin - (x &rest others)
1283   (let ((args (cons x others)))
1284     (variable-arity args
1285       (if (null others)
1286           (concat "-" (car args))
1287           (join args "-")))))
1288
1289 (define-raw-builtin * (&rest numbers)
1290   (if (null numbers)
1291       "1"
1292       (variable-arity numbers
1293         (join numbers "*"))))
1294
1295 (define-raw-builtin / (x &rest others)
1296   (let ((args (cons x others)))
1297     (variable-arity args
1298       (if (null others)
1299           (concat "1 /" (car args))
1300           (join args "/")))))
1301
1302 (define-builtin mod (x y) (num-op-num x "%" y))
1303
1304
1305 (defun comparison-conjuntion (vars op)
1306   (cond
1307     ((null (cdr vars))
1308      "true")
1309     ((null (cddr vars))
1310      (concat (car vars) op (cadr vars)))
1311     (t
1312      (concat (car vars) op (cadr vars)
1313              " && "
1314              (comparison-conjuntion (cdr vars) op)))))
1315
1316 (defmacro define-builtin-comparison (op sym)
1317   `(define-raw-builtin ,op (x &rest args)
1318      (let ((args (cons x args)))
1319        (variable-arity args
1320          (js!bool (comparison-conjuntion args ,sym))))))
1321
1322 (define-builtin-comparison > ">")
1323 (define-builtin-comparison < "<")
1324 (define-builtin-comparison >= ">=")
1325 (define-builtin-comparison <= "<=")
1326 (define-builtin-comparison = "==")
1327
1328 (define-builtin numberp (x)
1329   (js!bool (code "(typeof (" x ") == \"number\")")))
1330
1331 (define-builtin floor (x)
1332   (type-check (("x" "number" x))
1333     "Math.floor(x)"))
1334
1335 (define-builtin expt (x y)
1336   (type-check (("x" "number" x)
1337                ("y" "number" y))
1338     "Math.pow(x, y)"))
1339
1340 (define-builtin float-to-string (x)
1341   (type-check (("x" "number" x))
1342     "make_lisp_string(x.toString())"))
1343
1344 (define-builtin cons (x y)
1345   (code "({car: " x ", cdr: " y "})"))
1346
1347 (define-builtin consp (x)
1348   (js!bool
1349    (js!selfcall
1350      "var tmp = " x ";" *newline*
1351      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1352
1353 (define-builtin car (x)
1354   (js!selfcall
1355     "var tmp = " x ";" *newline*
1356     "return tmp === " (ls-compile nil)
1357     "? " (ls-compile nil)
1358     ": tmp.car;" *newline*))
1359
1360 (define-builtin cdr (x)
1361   (js!selfcall
1362     "var tmp = " x ";" *newline*
1363     "return tmp === " (ls-compile nil) "? "
1364     (ls-compile nil)
1365     ": tmp.cdr;" *newline*))
1366
1367 (define-builtin rplaca (x new)
1368   (type-check (("x" "object" x))
1369     (code "(x.car = " new ", x)")))
1370
1371 (define-builtin rplacd (x new)
1372   (type-check (("x" "object" x))
1373     (code "(x.cdr = " new ", x)")))
1374
1375 (define-builtin symbolp (x)
1376   (js!bool (code "(" x " instanceof Symbol)")))
1377
1378 (define-builtin make-symbol (name)
1379   (code "(new Symbol(" name "))"))
1380
1381 (define-builtin symbol-name (x)
1382   (code "(" x ").name"))
1383
1384 (define-builtin set (symbol value)
1385   (code "(" symbol ").value = " value))
1386
1387 (define-builtin fset (symbol value)
1388   (code "(" symbol ").fvalue = " value))
1389
1390 (define-builtin boundp (x)
1391   (js!bool (code "(" x ".value !== undefined)")))
1392
1393 (define-builtin symbol-value (x)
1394   (js!selfcall
1395     "var symbol = " x ";" *newline*
1396     "var value = symbol.value;" *newline*
1397     "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1398     "return value;" *newline*))
1399
1400 (define-builtin symbol-function (x)
1401   (js!selfcall
1402     "var symbol = " x ";" *newline*
1403     "var func = symbol.fvalue;" *newline*
1404     "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1405     "return func;" *newline*))
1406
1407 (define-builtin symbol-plist (x)
1408   (code "((" x ").plist || " (ls-compile nil) ")"))
1409
1410 (define-builtin lambda-code (x)
1411   (code "make_lisp_string((" x ").toString())"))
1412
1413 (define-builtin eq (x y)
1414   (js!bool (code "(" x " === " y ")")))
1415
1416 (define-builtin char-code (x)
1417   (type-check (("x" "string" x))
1418     "x.charCodeAt(0)"))
1419
1420 (define-builtin code-char (x)
1421   (type-check (("x" "number" x))
1422     "String.fromCharCode(x)"))
1423
1424 (define-builtin characterp (x)
1425   (js!bool
1426    (js!selfcall
1427      "var x = " x ";" *newline*
1428      "return (typeof(" x ") == \"string\") && x.length == 1;")))
1429
1430 (define-builtin char-to-string (x)
1431   (js!selfcall
1432     "var r = [" x "];" *newline*
1433     "r.type = 'character';"
1434     "return r"))
1435
1436 (define-builtin char-upcase (x)
1437   (code x ".toUpperCase()"))
1438
1439 (define-builtin char-downcase (x)
1440   (code x ".toLowerCase()"))
1441
1442 (define-builtin stringp (x)
1443   (js!bool
1444    (js!selfcall
1445      "var x = " x ";" *newline*
1446      "return typeof(x) == 'object' && 'length' in x && x.type == 'character';")))
1447
1448 (define-builtin string-upcase (x)
1449   (code "make_lisp_string(xstring(" x ").toUpperCase())"))
1450
1451 (define-builtin string-length (x)
1452   (code x ".length"))
1453
1454 (define-raw-builtin slice (vector a &optional b)
1455   (js!selfcall
1456     "var vector = " (ls-compile vector) ";" *newline*
1457     "var a = " (ls-compile a) ";" *newline*
1458     "var b;" *newline*
1459     (when b (code "b = " (ls-compile b) ";" *newline*))
1460     "return vector.slice(a,b);" *newline*))
1461
1462 (define-builtin char (string index)
1463   (code string "[" index "]"))
1464
1465 (define-builtin concat-two (string1 string2)
1466   (js!selfcall
1467     "var r = " string1 ".concat(" string2 ");" *newline*
1468     "r.type = 'character';"
1469     "return r;" *newline*))
1470
1471 (define-raw-builtin funcall (func &rest args)
1472   (js!selfcall
1473     "var f = " (ls-compile func) ";" *newline*
1474     "return (typeof f === 'function'? f: f.fvalue)("
1475     (join (list* (if *multiple-value-p* "values" "pv")
1476                  (integer-to-string (length args))
1477                  (mapcar #'ls-compile args))
1478           ", ")
1479     ")"))
1480
1481 (define-raw-builtin apply (func &rest args)
1482   (if (null args)
1483       (code "(" (ls-compile func) ")()")
1484       (let ((args (butlast args))
1485             (last (car (last args))))
1486         (js!selfcall
1487           "var f = " (ls-compile func) ";" *newline*
1488           "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1489                                       (integer-to-string (length args))
1490                                       (mapcar #'ls-compile args))
1491                                ", ")
1492           "];" *newline*
1493           "var tail = (" (ls-compile last) ");" *newline*
1494           "while (tail != " (ls-compile nil) "){" *newline*
1495           "    args.push(tail.car);" *newline*
1496           "    args[1] += 1;" *newline*
1497           "    tail = tail.cdr;" *newline*
1498           "}" *newline*
1499           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1500
1501 (define-builtin js-eval (string)
1502   (if *multiple-value-p*
1503       (js!selfcall
1504         "var v = globalEval(xstring(" string "));" *newline*
1505         "return values.apply(this, forcemv(v));" *newline*)
1506       (code "globalEval(xstring(" string "))")))
1507
1508 (define-builtin %throw (string)
1509   (js!selfcall "throw " string ";" *newline*))
1510
1511 (define-builtin new () "{}")
1512
1513 (define-builtin objectp (x)
1514   (js!bool (code "(typeof (" x ") === 'object')")))
1515
1516 (define-builtin oget (object key)
1517   (js!selfcall
1518     "var tmp = " "(" object ")[xstring(" key ")];" *newline*
1519     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1520
1521 (define-builtin oset (object key value)
1522   (code "((" object ")[xstring(" key ")] = " value ")"))
1523
1524 (define-builtin in (key object)
1525   (js!bool (code "(xstring(" key ") in (" object "))")))
1526
1527 (define-builtin functionp (x)
1528   (js!bool (code "(typeof " x " == 'function')")))
1529
1530 (define-builtin write-string (x)
1531   (code "lisp.write(" x ")"))
1532
1533 (define-builtin make-array (n)
1534   (js!selfcall
1535     "var r = [];" *newline*
1536     "for (var i = 0; i < " n "; i++)" *newline*
1537     (indent "r.push(" (ls-compile nil) ");" *newline*)
1538     "return r;" *newline*))
1539
1540 ;;; FIXME: should take optional min-extension.
1541 ;;; FIXME: should use fill-pointer instead of the absolute end of array
1542 (define-builtin vector-push-extend (new vector)
1543   (js!selfcall
1544     "var v = " vector ";" *newline*
1545     "v.push(" new ");" *newline*
1546     "return v;"))
1547
1548 (define-builtin arrayp (x)
1549   (js!bool
1550    (js!selfcall
1551      "var x = " x ";" *newline*
1552      "return typeof x === 'object' && 'length' in x;")))
1553
1554 (define-builtin aref (array n)
1555   (js!selfcall
1556     "var x = " "(" array ")[" n "];" *newline*
1557     "if (x === undefined) throw 'Out of range';" *newline*
1558     "return x;" *newline*))
1559
1560 (define-builtin aset (array n value)
1561   (js!selfcall
1562     "var x = " array ";" *newline*
1563     "var i = " n ";" *newline*
1564     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1565     "return x[i] = " value ";" *newline*))
1566
1567 (define-builtin afind (value array)
1568   (js!selfcall
1569     "var v = " value ";" *newline*
1570     "var x = " array ";" *newline*
1571     "return x.indexOf(v);" *newline*))
1572
1573 (define-builtin aresize (array new-size)
1574   (js!selfcall
1575     "var x = " array ";" *newline*
1576     "var n = " new-size ";" *newline*
1577     "return x.length = n;" *newline*))
1578
1579 (define-builtin get-internal-real-time ()
1580   "(new Date()).getTime()")
1581
1582 (define-builtin values-array (array)
1583   (if *multiple-value-p*
1584       (code "values.apply(this, " array ")")
1585       (code "pv.apply(this, " array ")")))
1586
1587 (define-raw-builtin values (&rest args)
1588   (if *multiple-value-p*
1589       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1590       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1591
1592
1593 ;;; Javascript FFI
1594
1595 (define-compilation %js-vref (var)
1596   (code "js_to_lisp(" var ")"))
1597
1598 (define-compilation %js-vset (var val)
1599   (code "(" var " = lisp_to_js(" (ls-compile val) "))"))
1600
1601 (define-setf-expander %js-vref (var)
1602   (let ((new-value (gensym)))
1603     (unless (stringp var)
1604       (error "`~S' is not a string." var))
1605     (values nil
1606             (list var)
1607             (list new-value)
1608             `(%js-vset ,var ,new-value)
1609             `(%js-vref ,var))))
1610
1611
1612 #+common-lisp
1613 (defvar *macroexpander-cache*
1614   (make-hash-table :test #'eq))
1615
1616 (defun !macro-function (symbol)
1617   (unless (symbolp symbol)
1618     (error "`~S' is not a symbol." symbol))
1619   (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1620     (if (and b (eq (binding-type b) 'macro))
1621         (let ((expander (binding-value b)))
1622           (cond
1623             #+common-lisp
1624             ((gethash b *macroexpander-cache*)
1625              (setq expander (gethash b *macroexpander-cache*)))
1626             ((listp expander)
1627              (let ((compiled (eval expander)))
1628                ;; The list representation are useful while
1629                ;; bootstrapping, as we can dump the definition of the
1630                ;; macros easily, but they are slow because we have to
1631                ;; evaluate them and compile them now and again. So, let
1632                ;; us replace the list representation version of the
1633                ;; function with the compiled one.
1634                ;;
1635                #+jscl (setf (binding-value b) compiled)
1636                #+common-lisp (setf (gethash b *macroexpander-cache*) compiled)
1637                (setq expander compiled))))
1638           expander)
1639         nil)))
1640
1641 (defun !macroexpand-1 (form)
1642   (cond
1643     ((symbolp form)
1644      (let ((b (lookup-in-lexenv form *environment* 'variable)))
1645        (if (and b (eq (binding-type b) 'macro))
1646            (values (binding-value b) t)
1647            (values form nil))))
1648     ((and (consp form) (symbolp (car form)))
1649      (let ((macrofun (!macro-function (car form))))
1650        (if macrofun
1651            (values (funcall macrofun (cdr form)) t)
1652            (values form nil))))
1653     (t
1654      (values form nil))))
1655
1656 (defun compile-funcall (function args)
1657   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1658          (arglist (concat "(" (join (list* values-funcs
1659                                            (integer-to-string (length args))
1660                                            (mapcar #'ls-compile args)) ", ") ")")))
1661     (unless (or (symbolp function)
1662                 (and (consp function)
1663                      (eq (car function) 'lambda)))
1664       (error "Bad function designator `~S'" function))
1665     (cond
1666       ((translate-function function)
1667        (concat (translate-function function) arglist))
1668       ((and (symbolp function)
1669             #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1670             #+common-lisp t)
1671        (code (ls-compile `',function) ".fvalue" arglist))
1672       (t
1673        (code (ls-compile `#',function) arglist)))))
1674
1675 (defun ls-compile-block (sexps &optional return-last-p)
1676   (if return-last-p
1677       (code (ls-compile-block (butlast sexps))
1678             "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1679       (join-trailing
1680        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1681        (concat ";" *newline*))))
1682
1683 (defun ls-compile (sexp &optional multiple-value-p)
1684   (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1685     (when expandedp
1686       (return-from ls-compile (ls-compile sexp multiple-value-p)))
1687     ;; The expression has been macroexpanded. Now compile it!
1688     (let ((*multiple-value-p* multiple-value-p))
1689       (cond
1690         ((symbolp sexp)
1691          (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1692            (cond
1693              ((and b (not (member 'special (binding-declarations b))))
1694               (binding-value b))
1695              ((or (keywordp sexp)
1696                   (and b (member 'constant (binding-declarations b))))
1697               (code (ls-compile `',sexp) ".value"))
1698              (t
1699               (ls-compile `(symbol-value ',sexp))))))
1700         ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1701          (literal sexp))
1702         ((listp sexp)
1703          (let ((name (car sexp))
1704                (args (cdr sexp)))
1705            (cond
1706              ;; Special forms
1707              ((assoc name *compilations*)
1708               (let ((comp (second (assoc name *compilations*))))
1709                 (apply comp args)))
1710              ;; Built-in functions
1711              ((and (assoc name *builtins*)
1712                    (not (claimp name 'function 'notinline)))
1713               (let ((comp (second (assoc name *builtins*))))
1714                 (apply comp args)))
1715              (t
1716               (compile-funcall name args)))))
1717         (t
1718          (error "How should I compile `~S'?" sexp))))))
1719
1720
1721 (defvar *compile-print-toplevels* nil)
1722
1723 (defun truncate-string (string &optional (width 60))
1724   (let ((n (or (position #\newline string)
1725                (min width (length string)))))
1726     (subseq string 0 n)))
1727
1728 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1729   (let ((*toplevel-compilations* nil))
1730     (cond
1731       ((and (consp sexp) (eq (car sexp) 'progn))
1732        (let ((subs (mapcar (lambda (s)
1733                              (ls-compile-toplevel s t))
1734                            (cdr sexp))))
1735          (join (remove-if #'null-or-empty-p subs))))
1736       (t
1737        (when *compile-print-toplevels*
1738          (let ((form-string (prin1-to-string sexp)))
1739            (format t "Compiling ~a..." (truncate-string form-string))))
1740        (let ((code (ls-compile sexp multiple-value-p)))
1741          (code (join-trailing (get-toplevel-compilations)
1742                               (code ";" *newline*))
1743                (when code
1744                  (code code ";" *newline*))))))))