Basic macrolet
[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 #-jscl
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 &optional 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 = " (js-escape-string name) ";" *newline*))
270         (when docstring
271           (code "func.docstring = " (js-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     (when (null pairs)
472       (return-from setq (ls-compile nil)))
473     (while t
474       (cond
475         ((null pairs)
476          (return))
477         ((null (cdr pairs))
478          (error "Odd pairs in SETQ"))
479         (t
480          (concatf result
481            (concat (setq-pair (car pairs) (cadr pairs))
482                    (if (null (cddr pairs)) "" ", ")))
483          (setq pairs (cddr pairs)))))
484     (code "(" result ")")))
485
486
487 ;;; Compilation of literals an object dumping
488
489 ;;; Two seperate functions are needed for escaping strings:
490 ;;;  One for producing JavaScript string literals (which are singly or
491 ;;;   doubly quoted)
492 ;;;  And one for producing Lisp strings (which are only doubly quoted)
493 ;;;
494 ;;; The same function would suffice for both, but for javascript string
495 ;;; literals it is neater to use either depending on the context, e.g:
496 ;;;  foo's => "foo's"
497 ;;;  "foo" => '"foo"'
498 ;;; which avoids having to escape quotes where possible
499 (defun js-escape-string (string)
500   (let ((index 0)
501         (size (length string))
502         (seen-single-quote nil)
503         (seen-double-quote nil))
504     (flet ((%js-escape-string (string escape-single-quote-p)
505              (let ((output "")
506                    (index 0))
507                (while (< index size)
508                  (let ((ch (char string index)))
509                    (when (char= ch #\\)
510                      (setq output (concat output "\\")))
511                    (when (and escape-single-quote-p (char= ch #\'))
512                      (setq output (concat output "\\")))
513                    (when (char= ch #\newline)
514                      (setq output (concat output "\\"))
515                      (setq ch #\n))
516                    (setq output (concat output (string ch))))
517                  (incf index))
518                output)))
519       ;; First, scan the string for single/double quotes
520       (while (< index size)
521         (let ((ch (char string index)))
522           (when (char= ch #\')
523             (setq seen-single-quote t))
524           (when (char= ch #\")
525             (setq seen-double-quote t)))
526         (incf index))
527       ;; Then pick the appropriate way to escape the quotes
528       (cond
529         ((not seen-single-quote)
530          (concat "'"   (%js-escape-string string nil) "'"))
531         ((not seen-double-quote)
532          (concat "\""  (%js-escape-string string nil) "\""))
533         (t (concat "'" (%js-escape-string string t)   "'"))))))
534
535 (defun lisp-escape-string (string)
536   (let ((output "")
537         (index 0)
538         (size (length string)))
539     (while (< index size)
540       (let ((ch (char string index)))
541         (when (or (char= ch #\") (char= ch #\\))
542           (setq output (concat output "\\")))
543         (when (or (char= ch #\newline))
544           (setq output (concat output "\\"))
545           (setq ch #\n))
546         (setq output (concat output (string ch))))
547       (incf index))
548     (concat "\"" output "\"")))
549
550 ;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
551 ;;; the bootstrap. Once everything is compiled, we want to dump the
552 ;;; whole global environment to the output file to reproduce it in the
553 ;;; run-time. However, the environment must contain expander functions
554 ;;; rather than lists. We do not know how to dump function objects
555 ;;; itself, so we mark the list definitions with this object and the
556 ;;; compiler will be called when this object has to be dumped.
557 ;;; Backquote/unquote does a similar magic, but this use is exclusive.
558 ;;;
559 ;;; Indeed, perhaps to compile the object other macros need to be
560 ;;; evaluated. For this reason we define a valid macro-function for
561 ;;; this symbol.
562 (defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
563 #-jscl
564 (setf (macro-function *magic-unquote-marker*)
565       (lambda (form &optional environment)
566         (declare (ignore environment))
567         (second form)))
568
569 (defvar *literal-table* nil)
570 (defvar *literal-counter* 0)
571
572 (defun genlit ()
573   (code "l" (incf *literal-counter*)))
574
575 (defun dump-symbol (symbol)
576   #-jscl
577   (let ((package (symbol-package symbol)))
578     (if (eq package (find-package "KEYWORD"))
579         (code "(new Symbol(" (dump-string (symbol-name symbol)) ", " (dump-string (package-name package)) "))")
580         (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")))
581   #+jscl
582   (let ((package (symbol-package symbol)))
583     (if (null package)
584         (code "(new Symbol(" (dump-string (symbol-name symbol)) "))")
585         (ls-compile `(intern ,(symbol-name symbol) ,(package-name package))))))
586
587 (defun dump-cons (cons)
588   (let ((head (butlast cons))
589         (tail (last cons)))
590     (code "QIList("
591           (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
592           (literal (car tail) t)
593           ","
594           (literal (cdr tail) t)
595           ")")))
596
597 (defun dump-array (array)
598   (let ((elements (vector-to-list array)))
599     (concat "[" (join (mapcar #'literal elements) ", ") "]")))
600
601 (defun dump-string (string)
602   (code "make_lisp_string(" (js-escape-string string) ")"))
603
604 (defun literal (sexp &optional recursive)
605   (cond
606     ((integerp sexp) (integer-to-string sexp))
607     ((floatp sexp) (float-to-string sexp))
608     ((characterp sexp) (js-escape-string (string sexp)))
609     (t
610      (or (cdr (assoc sexp *literal-table* :test #'eql))
611          (let ((dumped (typecase sexp
612                          (symbol (dump-symbol sexp))
613                          (string (dump-string sexp))
614                          (cons
615                           ;; BOOTSTRAP MAGIC: See the root file
616                           ;; jscl.lisp and the function
617                           ;; `dump-global-environment' for futher
618                           ;; information.
619                           (if (eq (car sexp) *magic-unquote-marker*)
620                               (ls-compile (second sexp))
621                               (dump-cons sexp)))
622                          (array (dump-array sexp)))))
623            (if (and recursive (not (symbolp sexp)))
624                dumped
625                (let ((jsvar (genlit)))
626                  (push (cons sexp jsvar) *literal-table*)
627                  (toplevel-compilation (code "var " jsvar " = " dumped))
628                  (when (keywordp sexp)
629                    (toplevel-compilation (code jsvar ".value = " jsvar)))
630                  jsvar)))))))
631
632
633 (define-compilation quote (sexp)
634   (literal sexp))
635
636 (define-compilation %while (pred &rest body)
637   (js!selfcall
638     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
639     (indent (ls-compile-block body))
640     "}"
641     "return " (ls-compile nil) ";" *newline*))
642
643 (define-compilation function (x)
644   (cond
645     ((and (listp x) (eq (car x) 'lambda))
646      (compile-lambda (cadr x) (cddr x)))
647     ((and (listp x) (eq (car x) 'named-lambda))
648      ;; TODO: destructuring-bind now! Do error checking manually is
649      ;; very annoying.
650      (let ((name (cadr x))
651            (ll (caddr x))
652            (body (cdddr x)))
653        (compile-lambda ll body
654                        :name (symbol-name name)
655                        :block name)))
656     ((symbolp x)
657      (let ((b (lookup-in-lexenv x *environment* 'function)))
658        (if b
659            (binding-value b)
660            (ls-compile `(symbol-function ',x)))))))
661
662
663 (defun make-function-binding (fname)
664   (make-binding :name fname :type 'function :value (gvarname fname)))
665
666 (defun compile-function-definition (list)
667   (compile-lambda (car list) (cdr list)))
668
669 (defun translate-function (name)
670   (let ((b (lookup-in-lexenv name *environment* 'function)))
671     (and b (binding-value b))))
672
673 (define-compilation flet (definitions &rest body)
674   (let* ((fnames (mapcar #'car definitions))
675          (cfuncs (mapcar (lambda (def)
676                            (compile-lambda (cadr def)
677                                            `((block ,(car def)
678                                                ,@(cddr def)))))
679                          definitions))
680          (*environment*
681           (extend-lexenv (mapcar #'make-function-binding fnames)
682                          *environment*
683                          'function)))
684     (code "(function("
685           (join (mapcar #'translate-function fnames) ",")
686           "){" *newline*
687           (let ((body (ls-compile-block body t)))
688             (indent body))
689           "})(" (join cfuncs ",") ")")))
690
691 (define-compilation labels (definitions &rest body)
692   (let* ((fnames (mapcar #'car definitions))
693          (*environment*
694           (extend-lexenv (mapcar #'make-function-binding fnames)
695                          *environment*
696                          'function)))
697     (js!selfcall
698       (mapconcat (lambda (func)
699                    (code "var " (translate-function (car func))
700                          " = " (compile-lambda (cadr func)
701                                                `((block ,(car func) ,@(cddr func))))
702                          ";" *newline*))
703                  definitions)
704       (ls-compile-block body t))))
705
706
707 (defvar *compiling-file* nil)
708 (define-compilation eval-when-compile (&rest body)
709   (if *compiling-file*
710       (progn
711         (eval (cons 'progn body))
712         nil)
713       (ls-compile `(progn ,@body))))
714
715 (defmacro define-transformation (name args form)
716   `(define-compilation ,name ,args
717      (ls-compile ,form)))
718
719 (define-compilation progn (&rest body)
720   (if (null (cdr body))
721       (ls-compile (car body) *multiple-value-p*)
722       (code "("
723             (join
724              (remove-if #'null-or-empty-p
725                         (append
726                          (mapcar #'ls-compile (butlast body))
727                          (list (ls-compile (car (last body)) t))))
728                   ",")
729             ")")))
730
731 (define-compilation macrolet (definitions &rest body)
732   (let ((*environment* (copy-lexenv *environment*)))
733     (dolist (def definitions)
734       (destructuring-bind (name lambda-list &body body) def
735         (let ((binding (make-binding :name name :type 'macro :value
736                                      (let ((g!form (gensym)))
737                                        `(lambda (,g!form)
738                                           (destructuring-bind ,lambda-list ,g!form
739                                             ,@body))))))
740           (push-to-lexenv binding  *environment* 'function))))
741     (ls-compile `(progn ,@body) *multiple-value-p*)))
742
743
744 (defun special-variable-p (x)
745   (and (claimp x 'variable 'special) t))
746
747 ;;; Wrap CODE to restore the symbol values of the dynamic
748 ;;; bindings. BINDINGS is a list of pairs of the form
749 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
750 ;;; name to initialize the symbol value and where to stored
751 ;;; the old value.
752 (defun let-binding-wrapper (bindings body)
753   (when (null bindings)
754     (return-from let-binding-wrapper body))
755   (code
756    "try {" *newline*
757    (indent "var tmp;" *newline*
758            (mapconcat
759             (lambda (b)
760               (let ((s (ls-compile `(quote ,(car b)))))
761                 (code "tmp = " s ".value;" *newline*
762                       s ".value = " (cdr b) ";" *newline*
763                       (cdr b) " = tmp;" *newline*)))
764             bindings)
765            body *newline*)
766    "}" *newline*
767    "finally {"  *newline*
768    (indent
769     (mapconcat (lambda (b)
770                  (let ((s (ls-compile `(quote ,(car b)))))
771                    (code s ".value" " = " (cdr b) ";" *newline*)))
772                bindings))
773    "}" *newline*))
774
775 (define-compilation let (bindings &rest body)
776   (let* ((bindings (mapcar #'ensure-list bindings))
777          (variables (mapcar #'first bindings))
778          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
779          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
780          (dynamic-bindings))
781     (code "(function("
782           (join (mapcar (lambda (x)
783                           (if (special-variable-p x)
784                               (let ((v (gvarname x)))
785                                 (push (cons x v) dynamic-bindings)
786                                 v)
787                               (translate-variable x)))
788                         variables)
789                 ",")
790           "){" *newline*
791           (let ((body (ls-compile-block body t t)))
792             (indent (let-binding-wrapper dynamic-bindings body)))
793           "})(" (join cvalues ",") ")")))
794
795
796 ;;; Return the code to initialize BINDING, and push it extending the
797 ;;; current lexical environment if the variable is not special.
798 (defun let*-initialize-value (binding)
799   (let ((var (first binding))
800         (value (second binding)))
801     (if (special-variable-p var)
802         (code (ls-compile `(setq ,var ,value)) ";" *newline*)
803         (let* ((v (gvarname var))
804                (b (make-binding :name var :type 'variable :value v)))
805           (prog1 (code "var " v " = " (ls-compile value) ";" *newline*)
806             (push-to-lexenv b *environment* 'variable))))))
807
808 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
809 ;;; DOES NOT generate code to initialize the value of the symbols,
810 ;;; unlike let-binding-wrapper.
811 (defun let*-binding-wrapper (symbols body)
812   (when (null symbols)
813     (return-from let*-binding-wrapper body))
814   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
815                        (remove-if-not #'special-variable-p symbols))))
816     (code
817      "try {" *newline*
818      (indent
819       (mapconcat (lambda (b)
820                    (let ((s (ls-compile `(quote ,(car b)))))
821                      (code "var " (cdr b) " = " s ".value;" *newline*)))
822                  store)
823       body)
824      "}" *newline*
825      "finally {" *newline*
826      (indent
827       (mapconcat (lambda (b)
828                    (let ((s (ls-compile `(quote ,(car b)))))
829                      (code s ".value" " = " (cdr b) ";" *newline*)))
830                  store))
831      "}" *newline*)))
832
833 (define-compilation let* (bindings &rest body)
834   (let ((bindings (mapcar #'ensure-list bindings))
835         (*environment* (copy-lexenv *environment*)))
836     (js!selfcall
837       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
838             (body (concat (mapconcat #'let*-initialize-value bindings)
839                           (ls-compile-block body t t))))
840         (let*-binding-wrapper specials body)))))
841
842
843 (define-compilation block (name &rest body)
844   ;; We use Javascript exceptions to implement non local control
845   ;; transfer. Exceptions has dynamic scoping, so we use a uniquely
846   ;; generated object to identify the block. The instance of a empty
847   ;; array is used to distinguish between nested dynamic Javascript
848   ;; exceptions. See https://github.com/davazp/jscl/issues/64 for
849   ;; futher details.
850   (let* ((idvar (gvarname name))
851          (b (make-binding :name name :type 'block :value idvar)))
852     (when *multiple-value-p*
853       (push 'multiple-value (binding-declarations b)))
854     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
855            (cbody (ls-compile-block body t)))
856       (if (member 'used (binding-declarations b))
857           (js!selfcall
858             "try {" *newline*
859             "var " idvar " = [];" *newline*
860             (indent cbody)
861             "}" *newline*
862             "catch (cf){" *newline*
863             "    if (cf.type == 'block' && cf.id == " idvar ")" *newline*
864             (if *multiple-value-p*
865                 "        return values.apply(this, forcemv(cf.values));"
866                 "        return cf.values;")
867             *newline*
868             "    else" *newline*
869             "        throw cf;" *newline*
870             "}" *newline*)
871           (js!selfcall cbody)))))
872
873 (define-compilation return-from (name &optional value)
874   (let* ((b (lookup-in-lexenv name *environment* 'block))
875          (multiple-value-p (member 'multiple-value (binding-declarations b))))
876     (when (null b)
877       (error "Return from unknown block `~S'." (symbol-name name)))
878     (push 'used (binding-declarations b))
879     ;; The binding value is the name of a variable, whose value is the
880     ;; unique identifier of the block as exception. We can't use the
881     ;; variable name itself, because it could not to be unique, so we
882     ;; capture it in a closure.
883     (js!selfcall
884       (when multiple-value-p (code "var values = mv;" *newline*))
885       "throw ({"
886       "type: 'block', "
887       "id: " (binding-value b) ", "
888       "values: " (ls-compile value multiple-value-p) ", "
889       "message: 'Return from unknown block " (symbol-name name) ".'"
890       "})")))
891
892 (define-compilation catch (id &rest body)
893   (js!selfcall
894     "var id = " (ls-compile id) ";" *newline*
895     "try {" *newline*
896     (indent (ls-compile-block body t)) *newline*
897     "}" *newline*
898     "catch (cf){" *newline*
899     "    if (cf.type == 'catch' && cf.id == id)" *newline*
900     (if *multiple-value-p*
901         "        return values.apply(this, forcemv(cf.values));"
902         "        return pv.apply(this, forcemv(cf.values));")
903     *newline*
904     "    else" *newline*
905     "        throw cf;" *newline*
906     "}" *newline*))
907
908 (define-compilation throw (id value)
909   (js!selfcall
910     "var values = mv;" *newline*
911     "throw ({"
912     "type: 'catch', "
913     "id: " (ls-compile id) ", "
914     "values: " (ls-compile value t) ", "
915     "message: 'Throw uncatched.'"
916     "})"))
917
918 (defun go-tag-p (x)
919   (or (integerp x) (symbolp x)))
920
921 (defun declare-tagbody-tags (tbidx body)
922   (let* ((go-tag-counter 0)
923          (bindings
924           (mapcar (lambda (label)
925                     (let ((tagidx (integer-to-string (incf go-tag-counter))))
926                       (make-binding :name label :type 'gotag :value (list tbidx tagidx))))
927                   (remove-if-not #'go-tag-p body))))
928     (extend-lexenv bindings *environment* 'gotag)))
929
930 (define-compilation tagbody (&rest body)
931   ;; Ignore the tagbody if it does not contain any go-tag. We do this
932   ;; because 1) it is easy and 2) many built-in forms expand to a
933   ;; implicit tagbody, so we save some space.
934   (unless (some #'go-tag-p body)
935     (return-from tagbody (ls-compile `(progn ,@body nil))))
936   ;; The translation assumes the first form in BODY is a label
937   (unless (go-tag-p (car body))
938     (push (gensym "START") body))
939   ;; Tagbody compilation
940   (let ((branch (gvarname 'branch))
941         (tbidx (gvarname 'tbidx)))
942     (let ((*environment* (declare-tagbody-tags tbidx body))
943           initag)
944       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
945         (setq initag (second (binding-value b))))
946       (js!selfcall
947         ;; TAGBODY branch to take
948         "var " branch " = " initag ";" *newline*
949         "var " tbidx " = [];" *newline*
950         "tbloop:" *newline*
951         "while (true) {" *newline*
952         (indent "try {" *newline*
953                 (indent (let ((content ""))
954                           (code "switch(" branch "){" *newline*
955                                 "case " initag ":" *newline*
956                                 (dolist (form (cdr body) content)
957                                   (concatf content
958                                     (if (not (go-tag-p form))
959                                         (indent (ls-compile form) ";" *newline*)
960                                         (let ((b (lookup-in-lexenv form *environment* 'gotag)))
961                                           (code "case " (second (binding-value b)) ":" *newline*)))))
962                                 "default:" *newline*
963                                 "    break tbloop;" *newline*
964                                 "}" *newline*)))
965                 "}" *newline*
966                 "catch (jump) {" *newline*
967                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
968                 "        " branch " = jump.label;" *newline*
969                 "    else" *newline*
970                 "        throw(jump);" *newline*
971                 "}" *newline*)
972         "}" *newline*
973         "return " (ls-compile nil) ";" *newline*))))
974
975 (define-compilation go (label)
976   (let ((b (lookup-in-lexenv label *environment* 'gotag))
977         (n (cond
978              ((symbolp label) (symbol-name label))
979              ((integerp label) (integer-to-string label)))))
980     (when (null b)
981       (error "Unknown tag `~S'" label))
982     (js!selfcall
983       "throw ({"
984       "type: 'tagbody', "
985       "id: " (first (binding-value b)) ", "
986       "label: " (second (binding-value b)) ", "
987       "message: 'Attempt to GO to non-existing tag " n "'"
988       "})" *newline*)))
989
990 (define-compilation unwind-protect (form &rest clean-up)
991   (js!selfcall
992     "var ret = " (ls-compile nil) ";" *newline*
993     "try {" *newline*
994     (indent "ret = " (ls-compile form) ";" *newline*)
995     "} finally {" *newline*
996     (indent (ls-compile-block clean-up))
997     "}" *newline*
998     "return ret;" *newline*))
999
1000 (define-compilation multiple-value-call (func-form &rest forms)
1001   (js!selfcall
1002     "var func = " (ls-compile func-form) ";" *newline*
1003     "var args = [" (if *multiple-value-p* "values" "pv") ", 0];" *newline*
1004     "return "
1005     (js!selfcall
1006       "var values = mv;" *newline*
1007       "var vs;" *newline*
1008       (mapconcat (lambda (form)
1009                    (code "vs = " (ls-compile form t) ";" *newline*
1010                          "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1011                          (indent "args = args.concat(vs);" *newline*)
1012                          "else" *newline*
1013                          (indent "args.push(vs);" *newline*)))
1014                  forms)
1015       "args[1] = args.length-2;" *newline*
1016       "return func.apply(window, args);" *newline*) ";" *newline*))
1017
1018 (define-compilation multiple-value-prog1 (first-form &rest forms)
1019   (js!selfcall
1020     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1021     (ls-compile-block forms)
1022     "return args;" *newline*))
1023
1024 (define-transformation backquote (form)
1025   (bq-completely-process form))
1026
1027
1028 ;;; Primitives
1029
1030 (defvar *builtins* nil)
1031
1032 (defmacro define-raw-builtin (name args &body body)
1033   ;; Creates a new primitive function `name' with parameters args and
1034   ;; @body. The body can access to the local environment through the
1035   ;; variable *ENVIRONMENT*.
1036   `(push (list ',name (lambda ,args (block ,name ,@body)))
1037          *builtins*))
1038
1039 (defmacro define-builtin (name args &body body)
1040   `(define-raw-builtin ,name ,args
1041      (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1042        ,@body)))
1043
1044 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1045 (defmacro type-check (decls &body body)
1046   `(js!selfcall
1047      ,@(mapcar (lambda (decl)
1048                  `(code "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1049                decls)
1050      ,@(mapcar (lambda (decl)
1051                  `(code "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1052                         (indent "throw 'The value ' + "
1053                                 ,(first decl)
1054                                 " + ' is not a type "
1055                                 ,(second decl)
1056                                 ".';"
1057                                 *newline*)))
1058                decls)
1059      (code "return " (progn ,@body) ";" *newline*)))
1060
1061 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1062 ;;; a variable which holds a list of forms. It will compile them and
1063 ;;; store the result in some Javascript variables. BODY is evaluated
1064 ;;; with ARGS bound to the list of these variables to generate the
1065 ;;; code which performs the transformation on these variables.
1066
1067 (defun variable-arity-call (args function)
1068   (unless (consp args)
1069     (error "ARGS must be a non-empty list"))
1070   (let ((counter 0)
1071         (fargs '())
1072         (prelude ""))
1073     (dolist (x args)
1074       (cond
1075         ((floatp x) (push (float-to-string x) fargs))
1076         ((numberp x) (push (integer-to-string x) fargs))
1077         (t (let ((v (code "x" (incf counter))))
1078              (push v fargs)
1079              (concatf prelude
1080                (code "var " v " = " (ls-compile x) ";" *newline*
1081                      "if (typeof " v " !== 'number') throw 'Not a number!';"
1082                      *newline*))))))
1083     (js!selfcall prelude (funcall function (reverse fargs)))))
1084
1085
1086 (defmacro variable-arity (args &body body)
1087   (unless (symbolp args)
1088     (error "`~S' is not a symbol." args))
1089   `(variable-arity-call ,args
1090                         (lambda (,args)
1091                           (code "return " ,@body ";" *newline*))))
1092
1093 (defun num-op-num (x op y)
1094   (type-check (("x" "number" x) ("y" "number" y))
1095     (code "x" op "y")))
1096
1097 (define-raw-builtin + (&rest numbers)
1098   (if (null numbers)
1099       "0"
1100       (variable-arity numbers
1101         (join numbers "+"))))
1102
1103 (define-raw-builtin - (x &rest others)
1104   (let ((args (cons x others)))
1105     (variable-arity args
1106       (if (null others)
1107           (concat "-" (car args))
1108           (join args "-")))))
1109
1110 (define-raw-builtin * (&rest numbers)
1111   (if (null numbers)
1112       "1"
1113       (variable-arity numbers
1114         (join numbers "*"))))
1115
1116 (define-raw-builtin / (x &rest others)
1117   (let ((args (cons x others)))
1118     (variable-arity args
1119       (if (null others)
1120           (concat "1 /" (car args))
1121           (join args "/")))))
1122
1123 (define-builtin mod (x y) (num-op-num x "%" y))
1124
1125
1126 (defun comparison-conjuntion (vars op)
1127   (cond
1128     ((null (cdr vars))
1129      "true")
1130     ((null (cddr vars))
1131      (concat (car vars) op (cadr vars)))
1132     (t
1133      (concat (car vars) op (cadr vars)
1134              " && "
1135              (comparison-conjuntion (cdr vars) op)))))
1136
1137 (defmacro define-builtin-comparison (op sym)
1138   `(define-raw-builtin ,op (x &rest args)
1139      (let ((args (cons x args)))
1140        (variable-arity args
1141          (js!bool (comparison-conjuntion args ,sym))))))
1142
1143 (define-builtin-comparison > ">")
1144 (define-builtin-comparison < "<")
1145 (define-builtin-comparison >= ">=")
1146 (define-builtin-comparison <= "<=")
1147 (define-builtin-comparison = "==")
1148 (define-builtin-comparison /= "!=")
1149
1150 (define-builtin numberp (x)
1151   (js!bool (code "(typeof (" x ") == \"number\")")))
1152
1153 (define-builtin floor (x)
1154   (type-check (("x" "number" x))
1155     "Math.floor(x)"))
1156
1157 (define-builtin expt (x y)
1158   (type-check (("x" "number" x)
1159                ("y" "number" y))
1160     "Math.pow(x, y)"))
1161
1162 (define-builtin float-to-string (x)
1163   (type-check (("x" "number" x))
1164     "make_lisp_string(x.toString())"))
1165
1166 (define-builtin cons (x y)
1167   (code "({car: " x ", cdr: " y "})"))
1168
1169 (define-builtin consp (x)
1170   (js!bool
1171    (js!selfcall
1172      "var tmp = " x ";" *newline*
1173      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1174
1175 (define-builtin car (x)
1176   (js!selfcall
1177     "var tmp = " x ";" *newline*
1178     "return tmp === " (ls-compile nil)
1179     "? " (ls-compile nil)
1180     ": tmp.car;" *newline*))
1181
1182 (define-builtin cdr (x)
1183   (js!selfcall
1184     "var tmp = " x ";" *newline*
1185     "return tmp === " (ls-compile nil) "? "
1186     (ls-compile nil)
1187     ": tmp.cdr;" *newline*))
1188
1189 (define-builtin rplaca (x new)
1190   (type-check (("x" "object" x))
1191     (code "(x.car = " new ", x)")))
1192
1193 (define-builtin rplacd (x new)
1194   (type-check (("x" "object" x))
1195     (code "(x.cdr = " new ", x)")))
1196
1197 (define-builtin symbolp (x)
1198   (js!bool (code "(" x " instanceof Symbol)")))
1199
1200 (define-builtin make-symbol (name)
1201   (code "(new Symbol(" name "))"))
1202
1203 (define-builtin symbol-name (x)
1204   (code "(" x ").name"))
1205
1206 (define-builtin set (symbol value)
1207   (code "(" symbol ").value = " value))
1208
1209 (define-builtin fset (symbol value)
1210   (code "(" symbol ").fvalue = " value))
1211
1212 (define-builtin boundp (x)
1213   (js!bool (code "(" x ".value !== undefined)")))
1214
1215 (define-builtin fboundp (x)
1216   (js!bool (code "(" x ".fvalue !== undefined)")))
1217
1218 (define-builtin symbol-value (x)
1219   (js!selfcall
1220     "var symbol = " x ";" *newline*
1221     "var value = symbol.value;" *newline*
1222     "if (value === undefined) throw \"Variable `\" + xstring(symbol.name) + \"' is unbound.\";" *newline*
1223     "return value;" *newline*))
1224
1225 (define-builtin symbol-function (x)
1226   (js!selfcall
1227     "var symbol = " x ";" *newline*
1228     "var func = symbol.fvalue;" *newline*
1229     "if (func === undefined) throw \"Function `\" + xstring(symbol.name) + \"' is undefined.\";" *newline*
1230     "return func;" *newline*))
1231
1232 (define-builtin symbol-plist (x)
1233   (code "((" x ").plist || " (ls-compile nil) ")"))
1234
1235 (define-builtin lambda-code (x)
1236   (code "make_lisp_string((" x ").toString())"))
1237
1238 (define-builtin eq (x y)
1239   (js!bool (code "(" x " === " y ")")))
1240
1241 (define-builtin char-code (x)
1242   (type-check (("x" "string" x))
1243     "char_to_codepoint(x)"))
1244
1245 (define-builtin code-char (x)
1246   (type-check (("x" "number" x))
1247     "char_from_codepoint(x)"))
1248
1249 (define-builtin characterp (x)
1250   (js!bool
1251    (js!selfcall
1252      "var x = " x ";" *newline*
1253      "return (typeof(" x ") == \"string\") && (x.length == 1 || x.length == 2);")))
1254
1255 (define-builtin char-upcase (x)
1256   (code "safe_char_upcase(" x ")"))
1257
1258 (define-builtin char-downcase (x)
1259   (code "safe_char_downcase(" x ")"))
1260
1261 (define-builtin stringp (x)
1262   (js!bool
1263    (js!selfcall
1264      "var x = " x ";" *newline*
1265      "return typeof(x) == 'object' && 'length' in x && x.stringp == 1;")))
1266
1267 (define-raw-builtin funcall (func &rest args)
1268   (js!selfcall
1269     "var f = " (ls-compile func) ";" *newline*
1270     "return (typeof f === 'function'? f: f.fvalue)("
1271     (join (list* (if *multiple-value-p* "values" "pv")
1272                  (integer-to-string (length args))
1273                  (mapcar #'ls-compile args))
1274           ", ")
1275     ")"))
1276
1277 (define-raw-builtin apply (func &rest args)
1278   (if (null args)
1279       (code "(" (ls-compile func) ")()")
1280       (let ((args (butlast args))
1281             (last (car (last args))))
1282         (js!selfcall
1283           "var f = " (ls-compile func) ";" *newline*
1284           "var args = [" (join (list* (if *multiple-value-p* "values" "pv")
1285                                       (integer-to-string (length args))
1286                                       (mapcar #'ls-compile args))
1287                                ", ")
1288           "];" *newline*
1289           "var tail = (" (ls-compile last) ");" *newline*
1290           "while (tail != " (ls-compile nil) "){" *newline*
1291           "    args.push(tail.car);" *newline*
1292           "    args[1] += 1;" *newline*
1293           "    tail = tail.cdr;" *newline*
1294           "}" *newline*
1295           "return (typeof f === 'function'? f : f.fvalue).apply(this, args);" *newline*))))
1296
1297 (define-builtin js-eval (string)
1298   (if *multiple-value-p*
1299       (js!selfcall
1300         "var v = globalEval(xstring(" string "));" *newline*
1301         "return values.apply(this, forcemv(v));" *newline*)
1302       (code "globalEval(xstring(" string "))")))
1303
1304 (define-builtin %throw (string)
1305   (js!selfcall "throw " string ";" *newline*))
1306
1307 (define-builtin functionp (x)
1308   (js!bool (code "(typeof " x " == 'function')")))
1309
1310 (define-builtin write-string (x)
1311   (code "lisp.write(" x ")"))
1312
1313
1314 ;;; Storage vectors. They are used to implement arrays and (in the
1315 ;;; future) structures.
1316
1317 (define-builtin storage-vector-p (x)
1318   (js!bool
1319    (js!selfcall
1320      "var x = " x ";" *newline*
1321      "return typeof x === 'object' && 'length' in x;")))
1322
1323 (define-builtin make-storage-vector (n)
1324   (js!selfcall
1325     "var r = [];" *newline*
1326     "r.length = " n ";" *newline*
1327     "return r;" *newline*))
1328
1329 (define-builtin storage-vector-size (x)
1330   (code x ".length"))
1331
1332 (define-builtin resize-storage-vector (vector new-size)
1333   (code "(" vector ".length = " new-size ")"))
1334
1335 (define-builtin storage-vector-ref (vector n)
1336   (js!selfcall
1337     "var x = " "(" vector ")[" n "];" *newline*
1338     "if (x === undefined) throw 'Out of range';" *newline*
1339     "return x;" *newline*))
1340
1341 (define-builtin storage-vector-set (vector n value)
1342   (js!selfcall
1343     "var x = " vector ";" *newline*
1344     "var i = " n ";" *newline*
1345     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
1346     "return x[i] = " value ";" *newline*))
1347
1348 (define-builtin concatenate-storage-vector (sv1 sv2)
1349   (js!selfcall
1350     "var sv1 = " sv1 ";" *newline*
1351     "var r = sv1.concat(" sv2 ");" *newline*
1352     "r.type = sv1.type;" *newline*
1353     "r.stringp = sv1.stringp;" *newline*
1354     "return r;" *newline*))
1355
1356 (define-builtin get-internal-real-time ()
1357   "(new Date()).getTime()")
1358
1359 (define-builtin values-array (array)
1360   (if *multiple-value-p*
1361       (code "values.apply(this, " array ")")
1362       (code "pv.apply(this, " array ")")))
1363
1364 (define-raw-builtin values (&rest args)
1365   (if *multiple-value-p*
1366       (code "values(" (join (mapcar #'ls-compile args) ", ") ")")
1367       (code "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
1368
1369
1370 ;;; Javascript FFI
1371
1372 (define-builtin new () "{}")
1373
1374 (define-raw-builtin oget* (object key &rest keys)
1375   (js!selfcall
1376     "var tmp = (" (ls-compile object) ")[xstring(" (ls-compile key) ")];" *newline*
1377     (mapconcat (lambda (key)
1378                  (code "if (tmp === undefined) return " (ls-compile nil) ";" *newline*
1379                        "tmp = tmp[xstring(" (ls-compile key) ")];" *newline*))
1380                keys)
1381     "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*))
1382
1383 (define-raw-builtin oset* (value object key &rest keys)
1384   (let ((keys (cons key keys)))
1385     (js!selfcall
1386       "var obj = " (ls-compile object) ";" *newline*
1387       (mapconcat (lambda (key)
1388                    (code "obj = obj[xstring(" (ls-compile key) ")];"
1389                          "if (obj === undefined) throw 'Impossible to set Javascript property.';" *newline*))
1390                  (butlast keys))
1391       "var tmp = obj[xstring(" (ls-compile (car (last keys))) ")] = " (ls-compile value) ";" *newline*
1392       "return tmp === undefined? " (ls-compile nil) " : tmp;" *newline*)))
1393
1394 (define-raw-builtin oget (object key &rest keys)
1395   (code "js_to_lisp(" (ls-compile `(oget* ,object ,key ,@keys)) ")"))
1396
1397 (define-raw-builtin oset (value object key &rest keys)
1398   (ls-compile `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
1399
1400 (define-builtin objectp (x)
1401   (js!bool (code "(typeof (" x ") === 'object')")))
1402
1403 (define-builtin lisp-to-js (x) (code "lisp_to_js(" x ")"))
1404 (define-builtin js-to-lisp (x) (code "js_to_lisp(" x ")"))
1405
1406
1407 (define-builtin in (key object)
1408   (js!bool (code "(xstring(" key ") in (" object "))")))
1409
1410 (define-builtin map-for-in (function object)
1411   (js!selfcall
1412    "var f = " function ";" *newline*
1413    "var g = (typeof f === 'function' ? f : f.fvalue);" *newline*
1414    "var o = " object ";" *newline*
1415    "for (var key in o){" *newline*
1416    (indent "g(" (if *multiple-value-p* "values" "pv") ", 1, o[key]);" *newline*)
1417    "}"
1418    " return " (ls-compile nil) ";" *newline*))
1419
1420 (define-compilation %js-vref (var)
1421   (code "js_to_lisp(" var ")"))
1422
1423 (define-compilation %js-vset (var val)
1424   (code "(" var " = lisp_to_js(" (ls-compile val) "))"))
1425
1426 (define-setf-expander %js-vref (var)
1427   (let ((new-value (gensym)))
1428     (unless (stringp var)
1429       (error "`~S' is not a string." var))
1430     (values nil
1431             (list var)
1432             (list new-value)
1433             `(%js-vset ,var ,new-value)
1434             `(%js-vref ,var))))
1435
1436
1437 #-jscl
1438 (defvar *macroexpander-cache*
1439   (make-hash-table :test #'eq))
1440
1441 (defun !macro-function (symbol)
1442   (unless (symbolp symbol)
1443     (error "`~S' is not a symbol." symbol))
1444   (let ((b (lookup-in-lexenv symbol *environment* 'function)))
1445     (if (and b (eq (binding-type b) 'macro))
1446         (let ((expander (binding-value b)))
1447           (cond
1448             #-jscl
1449             ((gethash b *macroexpander-cache*)
1450              (setq expander (gethash b *macroexpander-cache*)))
1451             ((listp expander)
1452              (let ((compiled (eval expander)))
1453                ;; The list representation are useful while
1454                ;; bootstrapping, as we can dump the definition of the
1455                ;; macros easily, but they are slow because we have to
1456                ;; evaluate them and compile them now and again. So, let
1457                ;; us replace the list representation version of the
1458                ;; function with the compiled one.
1459                ;;
1460                #+jscl (setf (binding-value b) compiled)
1461                #-jscl (setf (gethash b *macroexpander-cache*) compiled)
1462                (setq expander compiled))))
1463           expander)
1464         nil)))
1465
1466 (defun !macroexpand-1 (form)
1467   (cond
1468     ((symbolp form)
1469      (let ((b (lookup-in-lexenv form *environment* 'variable)))
1470        (if (and b (eq (binding-type b) 'macro))
1471            (values (binding-value b) t)
1472            (values form nil))))
1473     ((and (consp form) (symbolp (car form)))
1474      (let ((macrofun (!macro-function (car form))))
1475        (if macrofun
1476            (values (funcall macrofun (cdr form)) t)
1477            (values form nil))))
1478     (t
1479      (values form nil))))
1480
1481 (defun compile-funcall (function args)
1482   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
1483          (arglist (concat "(" (join (list* values-funcs
1484                                            (integer-to-string (length args))
1485                                            (mapcar #'ls-compile args)) ", ") ")")))
1486     (unless (or (symbolp function)
1487                 (and (consp function)
1488                      (member (car function) '(lambda oget))))
1489       (error "Bad function designator `~S'" function))
1490     (cond
1491       ((translate-function function)
1492        (concat (translate-function function) arglist))
1493       ((and (symbolp function)
1494             #+jscl (eq (symbol-package function) (find-package "COMMON-LISP"))
1495             #-jscl t)
1496        (code (ls-compile `',function) ".fvalue" arglist))
1497       #+jscl((symbolp function)
1498        (code (ls-compile `#',function) arglist))
1499       ((and (consp function) (eq (car function) 'lambda))
1500        (code (ls-compile `#',function) arglist))
1501       ((and (consp function) (eq (car function) 'oget))
1502        (code (ls-compile function) arglist))
1503       (t
1504        (error "Bad function descriptor")))))
1505
1506 (defun ls-compile-block (sexps &optional return-last-p decls-allowed-p)
1507   (multiple-value-bind (sexps decls)
1508       (parse-body sexps :declarations decls-allowed-p)
1509     (declare (ignore decls))
1510     (if return-last-p
1511         (code (ls-compile-block (butlast sexps) nil decls-allowed-p)
1512               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
1513         (join-trailing
1514          (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1515          (concat ";" *newline*)))))
1516
1517 (defun ls-compile (sexp &optional multiple-value-p)
1518   (multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
1519     (when expandedp
1520       (return-from ls-compile (ls-compile sexp multiple-value-p)))
1521     ;; The expression has been macroexpanded. Now compile it!
1522     (let ((*multiple-value-p* multiple-value-p))
1523       (cond
1524         ((symbolp sexp)
1525          (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1526            (cond
1527              ((and b (not (member 'special (binding-declarations b))))
1528               (binding-value b))
1529              ((or (keywordp sexp)
1530                   (and b (member 'constant (binding-declarations b))))
1531               (code (ls-compile `',sexp) ".value"))
1532              (t
1533               (ls-compile `(symbol-value ',sexp))))))
1534         ((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
1535          (literal sexp))
1536         ((listp sexp)
1537          (let ((name (car sexp))
1538                (args (cdr sexp)))
1539            (cond
1540              ;; Special forms
1541              ((assoc name *compilations*)
1542               (let ((comp (second (assoc name *compilations*))))
1543                 (apply comp args)))
1544              ;; Built-in functions
1545              ((and (assoc name *builtins*)
1546                    (not (claimp name 'function 'notinline)))
1547               (let ((comp (second (assoc name *builtins*))))
1548                 (apply comp args)))
1549              (t
1550               (compile-funcall name args)))))
1551         (t
1552          (error "How should I compile `~S'?" sexp))))))
1553
1554
1555 (defvar *compile-print-toplevels* nil)
1556
1557 (defun truncate-string (string &optional (width 60))
1558   (let ((n (or (position #\newline string)
1559                (min width (length string)))))
1560     (subseq string 0 n)))
1561
1562 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
1563   (let ((*toplevel-compilations* nil))
1564     (cond
1565       ((and (consp sexp) (eq (car sexp) 'progn))
1566        (let ((subs (mapcar (lambda (s)
1567                              (ls-compile-toplevel s t))
1568                            (cdr sexp))))
1569          (join (remove-if #'null-or-empty-p subs))))
1570       (t
1571        (when *compile-print-toplevels*
1572          (let ((form-string (prin1-to-string sexp)))
1573            (format t "Compiling ~a..." (truncate-string form-string))))
1574        (let ((code (ls-compile sexp multiple-value-p)))
1575          (code (join-trailing (get-toplevel-compilations)
1576                               (code ";" *newline*))
1577                (when code
1578                  (code code ";" *newline*))))))))