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