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