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