6a0447dc9b8a99f744374ab7d423400c4e5d2781
[jscl.git] / ecmalisp.lisp
1 ;;; ecmalisp.lisp ---
2
3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
6 ;; This program 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 ;; This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;;; This code is executed when ecmalisp compiles this file
20 ;;; itself. The compiler provides compilation of some special forms,
21 ;;; as well as funcalls and macroexpansion, but no functions. So, we
22 ;;; define the Lisp world from scratch. This code has to define enough
23 ;;; language to the compiler to be able to run.
24
25 #+ecmalisp
26 (progn
27   (eval-when-compile
28     (%compile-defmacro 'defmacro
29                        '(function
30                          (lambda (name args &rest body)
31                           `(eval-when-compile
32                              (%compile-defmacro ',name
33                                                 '(function
34                                                   (lambda ,(mapcar #'(lambda (x)
35                                                                        (if (eq x '&body)
36                                                                            '&rest
37                                                                            x))
38                                                                    args)
39                                                    ,@body))))))))
40
41   (defmacro declaim (&rest decls)
42     `(eval-when-compile
43        ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
44
45   (declaim (constant nil t) (special t nil))
46   (setq nil 'nil)
47   (js-vset "nil" nil)
48   (setq t 't)
49
50   (defmacro lambda (args &body body)
51     `(function (lambda ,args ,@body)))
52
53   (defmacro when (condition &body body)
54     `(if ,condition (progn ,@body) nil))
55
56   (defmacro unless (condition &body body)
57     `(if ,condition nil (progn ,@body)))
58
59   (defmacro defvar (name value &optional docstring)
60     `(progn
61        (declaim (special ,name))
62        (unless (boundp ',name) (setq ,name ,value))
63        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
64        ',name))
65
66   (defmacro defparameter (name value &optional docstring)
67     `(progn
68        (setq ,name ,value)
69        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
70        ',name))
71
72   (defmacro named-lambda (name args &rest body)
73     (let ((x (gensym "FN")))
74       `(let ((,x (lambda ,args ,@body)))
75          (oset ,x "fname" ,name)
76          ,x)))
77
78   (defmacro defun (name args &rest body)
79     `(progn
80        (fset ',name
81              (named-lambda ,(symbol-name name) ,args
82                ,@(if (and (stringp (car body)) (not (null (cdr body))))
83                      `(,(car body) (block ,name ,@(cdr body)))
84                      `((block ,name ,@body)))))
85        ',name))
86
87   (defun null (x)
88     (eq x nil))
89
90   (defmacro return (&optional value)
91     `(return-from nil ,value))
92
93   (defmacro while (condition &body body)
94     `(block nil (%while ,condition ,@body)))
95
96   (defvar *gensym-counter* 0)
97   (defun gensym (&optional (prefix "G"))
98     (setq *gensym-counter* (+ *gensym-counter* 1))
99     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
100
101   (defun boundp (x)
102     (boundp x))
103
104   ;; Basic functions
105   (defun = (x y) (= x y))
106   (defun * (x y) (* x y))
107   (defun / (x y) (/ x y))
108   (defun 1+ (x) (+ x 1))
109   (defun 1- (x) (- x 1))
110   (defun zerop (x) (= x 0))
111   (defun truncate (x y) (floor (/ x y)))
112
113   (defun eql (x y) (eq x y))
114
115   (defun not (x) (if x nil t))
116
117   (defun cons (x y ) (cons x y))
118   (defun consp (x) (consp x))
119
120   (defun car (x)
121     "Return the CAR part of a cons, or NIL if X is null."
122     (car x))
123
124   (defun cdr (x) (cdr x))
125   (defun caar (x) (car (car x)))
126   (defun cadr (x) (car (cdr x)))
127   (defun cdar (x) (cdr (car x)))
128   (defun cddr (x) (cdr (cdr x)))
129   (defun caddr (x) (car (cdr (cdr x))))
130   (defun cdddr (x) (cdr (cdr (cdr x))))
131   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
132   (defun first (x) (car x))
133   (defun second (x) (cadr x))
134   (defun third (x) (caddr x))
135   (defun fourth (x) (cadddr x))
136   (defun rest (x) (cdr x))
137
138   (defun list (&rest args) args)
139   (defun atom (x)
140     (not (consp x)))
141
142   ;; Basic macros
143
144   (defmacro incf (x &optional (delta 1))
145     `(setq ,x (+ ,x ,delta)))
146
147   (defmacro decf (x &optional (delta 1))
148     `(setq ,x (- ,x ,delta)))
149
150   (defmacro push (x place)
151     `(setq ,place (cons ,x ,place)))
152
153   (defmacro dolist (iter &body body)
154     (let ((var (first iter))
155           (g!list (gensym)))
156       `(block nil
157          (let ((,g!list ,(second iter))
158                (,var nil))
159            (%while ,g!list
160                    (setq ,var (car ,g!list))
161                    (tagbody ,@body)
162                    (setq ,g!list (cdr ,g!list)))
163            ,(third iter)))))
164
165   (defmacro dotimes (iter &body body)
166     (let ((g!to (gensym))
167           (var (first iter))
168           (to (second iter))
169           (result (third iter)))
170       `(block nil
171          (let ((,var 0)
172                (,g!to ,to))
173            (%while (< ,var ,g!to)
174                    (tagbody ,@body)
175                    (incf ,var))
176            ,result))))
177
178   (defmacro cond (&rest clausules)
179     (if (null clausules)
180         nil
181         (if (eq (caar clausules) t)
182             `(progn ,@(cdar clausules))
183             `(if ,(caar clausules)
184                  (progn ,@(cdar clausules))
185                  (cond ,@(cdr clausules))))))
186
187   (defmacro case (form &rest clausules)
188     (let ((!form (gensym)))
189       `(let ((,!form ,form))
190          (cond
191            ,@(mapcar (lambda (clausule)
192                        (if (eq (car clausule) t)
193                            clausule
194                            `((eql ,!form ',(car clausule))
195                              ,@(cdr clausule))))
196                      clausules)))))
197
198   (defmacro ecase (form &rest clausules)
199     `(case ,form
200        ,@(append
201           clausules
202           `((t
203              (error "ECASE expression failed."))))))
204
205   (defmacro and (&rest forms)
206     (cond
207       ((null forms)
208        t)
209       ((null (cdr forms))
210        (car forms))
211       (t
212        `(if ,(car forms)
213             (and ,@(cdr forms))
214             nil))))
215
216   (defmacro or (&rest forms)
217     (cond
218       ((null forms)
219        nil)
220       ((null (cdr forms))
221        (car forms))
222       (t
223        (let ((g (gensym)))
224          `(let ((,g ,(car forms)))
225             (if ,g ,g (or ,@(cdr forms))))))))
226
227   (defmacro prog1 (form &body body)
228     (let ((value (gensym)))
229       `(let ((,value ,form))
230          ,@body
231          ,value)))
232
233   (defmacro prog2 (form1 result &body body)
234     `(prog1 (progn ,form1 ,result) ,@body)))
235
236
237 ;;; This couple of helper functions will be defined in both Common
238 ;;; Lisp and in Ecmalisp.
239 (defun ensure-list (x)
240   (if (listp x)
241       x
242       (list x)))
243
244 (defun !reduce (func list initial)
245   (if (null list)
246       initial
247       (!reduce func
248                (cdr list)
249                (funcall func initial (car list)))))
250
251 ;;; Go on growing the Lisp language in Ecmalisp, with more high
252 ;;; level utilities as well as correct versions of other
253 ;;; constructions.
254 #+ecmalisp
255 (progn
256   (defun + (&rest args)
257     (let ((r 0))
258       (dolist (x args r)
259         (incf r x))))
260
261   (defun - (x &rest others)
262     (if (null others)
263         (- x)
264         (let ((r x))
265           (dolist (y others r)
266             (decf r y)))))
267
268   (defun append-two (list1 list2)
269     (if (null list1)
270         list2
271         (cons (car list1)
272               (append (cdr list1) list2))))
273
274   (defun append (&rest lists)
275     (!reduce #'append-two lists '()))
276
277   (defun revappend (list1 list2)
278     (while list1
279       (push (car list1) list2)
280       (setq list1 (cdr list1)))
281     list2)
282
283   (defun reverse (list)
284     (revappend list '()))
285
286   (defmacro psetq (&rest pairs)
287     (let ( ;; For each pair, we store here a list of the form
288           ;; (VARIABLE GENSYM VALUE).
289           (assignments '()))
290       (while t
291         (cond
292           ((null pairs) (return))
293           ((null (cdr pairs))
294            (error "Odd paris in PSETQ"))
295           (t
296            (let ((variable (car pairs))
297                  (value (cadr pairs)))
298              (push `(,variable ,(gensym) ,value)  assignments)
299              (setq pairs (cddr pairs))))))
300       (setq assignments (reverse assignments))
301       ;;
302       `(let ,(mapcar #'cdr assignments)
303          (setq ,@(!reduce #'append (mapcar #'butlast assignments) '())))))
304
305   (defmacro do (varlist endlist &body body)
306     `(block nil
307        (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
308          (while t
309            (when ,(car endlist)
310              (return (progn ,(cdr endlist))))
311            (tagbody ,@body)
312            (psetq
313             ,@(apply #'append
314                      (mapcar (lambda (v)
315                                (and (consp (cddr v))
316                                     (list (first v) (third v))))
317                              varlist)))))))
318
319   (defmacro do* (varlist endlist &body body)
320     `(block nil
321        (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
322          (while t
323            (when ,(car endlist)
324              (return (progn ,(cdr endlist))))
325            (tagbody ,@body)
326            (setq
327             ,@(apply #'append
328                      (mapcar (lambda (v)
329                                (and (consp (cddr v))
330                                     (list (first v) (third v))))
331                              varlist)))))))
332
333   (defun list-length (list)
334     (let ((l 0))
335       (while (not (null list))
336         (incf l)
337         (setq list (cdr list)))
338       l))
339
340   (defun length (seq)
341     (cond
342       ((stringp seq)
343        (string-length seq))
344       ((arrayp seq)
345        (oget seq "length"))
346       ((listp seq)
347        (list-length seq))))
348
349   (defun concat-two (s1 s2)
350     (concat-two s1 s2))
351
352   (defun mapcar (func list)
353     (let* ((head (cons 'sentinel nil))
354            (tail head))
355       (while (not (null list))
356         (let ((new (cons (funcall func (car list)) nil)))
357           (rplacd tail new)
358           (setq tail new
359                 list (cdr list))))
360       (cdr head)))
361
362   (defun identity (x) x)
363
364   (defun constantly (x)
365     (lambda (&rest args)
366       x))
367
368   (defun copy-list (x)
369     (mapcar #'identity x))
370
371   (defun code-char (x) x)
372   (defun char-code (x) x)
373   (defun char= (x y) (= x y))
374
375   (defun integerp (x)
376     (and (numberp x) (= (floor x) x)))
377
378   (defun plusp (x) (< 0 x))
379   (defun minusp (x) (< x 0))
380
381   (defun listp (x)
382     (or (consp x) (null x)))
383
384   (defun nthcdr (n list)
385     (while (and (plusp n) list)
386       (setq n (1- n))
387       (setq list (cdr list)))
388     list)
389
390   (defun nth (n list)
391     (car (nthcdr n list)))
392
393   (defun last (x)
394     (while (consp (cdr x))
395       (setq x (cdr x)))
396     x)
397
398   (defun butlast (x)
399     (and (consp (cdr x))
400          (cons (car x) (butlast (cdr x)))))
401
402   (defun member (x list)
403     (while list
404       (when (eql x (car list))
405         (return list))
406       (setq list (cdr list))))
407
408   (defun remove (x list)
409     (cond
410       ((null list)
411        nil)
412       ((eql x (car list))
413        (remove x (cdr list)))
414       (t
415        (cons (car list) (remove x (cdr list))))))
416
417   (defun remove-if (func list)
418     (cond
419       ((null list)
420        nil)
421       ((funcall func (car list))
422        (remove-if func (cdr list)))
423       (t
424        (cons (car list) (remove-if func (cdr list))))))
425
426   (defun remove-if-not (func list)
427     (cond
428       ((null list)
429        nil)
430       ((funcall func (car list))
431        (cons (car list) (remove-if-not func (cdr list))))
432       (t
433        (remove-if-not func (cdr list)))))
434
435   (defun digit-char-p (x)
436     (if (and (<= #\0 x) (<= x #\9))
437         (- x #\0)
438         nil))
439
440   (defun digit-char (weight)
441     (and (<= 0 weight 9)
442          (char "0123456789" weight)))  
443
444   (defun subseq (seq a &optional b)
445     (cond
446       ((stringp seq)
447        (if b
448            (slice seq a b)
449            (slice seq a)))
450       (t
451        (error "Unsupported argument."))))
452
453   (defun some (function seq)
454     (cond
455       ((stringp seq)
456        (let ((index 0)
457              (size (length seq)))
458          (while (< index size)
459            (when (funcall function (char seq index))
460              (return-from some t))
461            (incf index))
462          nil))
463       ((listp seq)
464        (dolist (x seq nil)
465          (when (funcall function x)
466            (return t))))
467       (t
468        (error "Unknown sequence."))))
469
470   (defun every (function seq)
471     (cond
472       ((stringp seq)
473        (let ((index 0)
474              (size (length seq)))
475          (while (< index size)
476            (unless (funcall function (char seq index))
477              (return-from every nil))
478            (incf index))
479          t))
480       ((listp seq)
481        (dolist (x seq t)
482          (unless (funcall function x)
483            (return))))
484       (t
485        (error "Unknown sequence."))))
486
487   (defun assoc (x alist)
488     (while alist
489       (if (eql x (caar alist))
490           (return)
491           (setq alist (cdr alist))))
492     (car alist))
493
494   (defun string (x)
495     (cond ((stringp x) x)
496           ((symbolp x) (symbol-name x))
497           (t (char-to-string x))))
498
499   (defun string= (s1 s2)
500     (equal s1 s2))
501
502   (defun fdefinition (x)
503     (cond
504       ((functionp x)
505        x)
506       ((symbolp x)
507        (symbol-function x))
508       (t
509        (error "Invalid function"))))
510
511   (defun disassemble (function)
512     (write-line (lambda-code (fdefinition function)))
513     nil)
514
515   (defun documentation (x type)
516     "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
517     (ecase type
518       (function
519        (let ((func (fdefinition x)))
520          (oget func "docstring")))
521       (variable
522        (unless (symbolp x)
523          (error "Wrong argument type! it should be a symbol"))
524        (oget x "vardoc"))))
525
526   (defmacro multiple-value-bind (variables value-from &body body)
527     `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
528                             ,@body)
529        ,value-from))
530
531   (defmacro multiple-value-list (value-from)
532     `(multiple-value-call #'list ,value-from))
533
534   ;; Packages
535
536   (defvar *package-list* nil)
537
538   (defun list-all-packages ()
539     *package-list*)
540
541   (defun make-package (name &optional use)
542     (let ((package (new))
543           (use (mapcar #'find-package-or-fail use)))
544       (oset package "packageName" name)
545       (oset package "symbols" (new))
546       (oset package "exports" (new))
547       (oset package "use" use)
548       (push package *package-list*)
549       package))
550
551   (defun packagep (x)
552     (and (objectp x) (in "symbols" x)))
553
554   (defun find-package (package-designator)
555     (when (packagep package-designator)
556       (return-from find-package package-designator))
557     (let ((name (string package-designator)))
558       (dolist (package *package-list*)
559         (when (string= (package-name package) name)
560           (return package)))))
561
562   (defun find-package-or-fail (package-designator)
563     (or (find-package package-designator)
564         (error "Package unknown.")))
565
566   (defun package-name (package-designator)
567     (let ((package (find-package-or-fail package-designator)))
568       (oget package "packageName")))
569
570   (defun %package-symbols (package-designator)
571     (let ((package (find-package-or-fail package-designator)))
572       (oget package "symbols")))
573
574   (defun package-use-list (package-designator)
575     (let ((package (find-package-or-fail package-designator)))
576       (oget package "use")))
577
578   (defun %package-external-symbols (package-designator)
579     (let ((package (find-package-or-fail package-designator)))
580       (oget package "exports")))
581
582   (defvar *common-lisp-package*
583     (make-package "CL"))
584
585   (defvar *user-package*
586     (make-package "CL-USER" (list *common-lisp-package*)))
587
588   (defvar *keyword-package*
589     (make-package "KEYWORD"))
590
591   (defun keywordp (x)
592     (and (symbolp x) (eq (symbol-package x) *keyword-package*)))
593
594   (defvar *package* *common-lisp-package*)
595
596   (defmacro in-package (package-designator)
597     `(eval-when-compile
598        (setq *package* (find-package-or-fail ,package-designator))))
599
600   ;; This function is used internally to initialize the CL package
601   ;; with the symbols built during bootstrap.
602   (defun %intern-symbol (symbol)
603     (let* ((package
604             (if (in "package" symbol)
605                 (find-package-or-fail (oget symbol "package"))
606                 *common-lisp-package*))
607            (symbols (%package-symbols package)))
608       (oset symbol "package" package)
609       (when (eq package *keyword-package*)
610         (oset symbol "value" symbol))
611       (oset symbols (symbol-name symbol) symbol)))
612
613   (defun find-symbol (name &optional (package *package*))
614     (let* ((package (find-package-or-fail package))
615            (externals (%package-external-symbols package))
616            (symbols (%package-symbols package)))
617       (cond
618         ((in name externals)
619          (values (oget externals name) :external))
620         ((in name symbols)
621          (values (oget symbols name) :internal))
622         (t
623          (dolist (used (package-use-list package) (values nil nil))
624            (let ((exports (%package-external-symbols used)))
625              (when (in name exports)
626                (return (values (oget exports name) :inherit)))))))))
627
628   (defun intern (name &optional (package *package*))
629     (let ((package (find-package-or-fail package)))
630       (multiple-value-bind (symbol foundp)
631           (find-symbol name package)
632         (if foundp
633             (values symbol foundp)
634             (let ((symbols (%package-symbols package)))
635               (oget symbols name)
636               (let ((symbol (make-symbol name)))
637                 (oset symbol "package" package)
638                 (when (eq package *keyword-package*)
639                   (oset symbol "value" symbol)
640                   (export (list symbol) package))
641                 (oset symbols name symbol)
642                 (values symbol nil)))))))
643
644   (defun symbol-package (symbol)
645     (unless (symbolp symbol)
646       (error "it is not a symbol"))
647     (oget symbol "package"))
648
649   (defun export (symbols &optional (package *package*))
650     (let ((exports (%package-external-symbols package)))
651       (dolist (symb symbols t)
652         (oset exports (symbol-name symb) symb))))
653
654   (defun get-universal-time ()
655     (+ (get-unix-time) 2208988800)))
656
657
658 ;;; The compiler offers some primitives and special forms which are
659 ;;; not found in Common Lisp, for instance, while. So, we grow Common
660 ;;; Lisp a bit to it can execute the rest of the file.
661 #+common-lisp
662 (progn
663   (defmacro while (condition &body body)
664     `(do ()
665          ((not ,condition))
666        ,@body))
667
668   (defmacro eval-when-compile (&body body)
669     `(eval-when (:compile-toplevel :load-toplevel :execute)
670        ,@body))
671
672   (defun concat-two (s1 s2)
673     (concatenate 'string s1 s2))
674
675   (defun aset (array idx value)
676     (setf (aref array idx) value)))
677
678 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
679 ;;; from here, this code will compile on both. We define some helper
680 ;;; functions now for string manipulation and so on. They will be
681 ;;; useful in the compiler, mostly.
682
683 (defvar *newline* (string (code-char 10)))
684
685 (defun concat (&rest strs)
686   (!reduce #'concat-two strs ""))
687
688 (defmacro concatf (variable &body form)
689   `(setq ,variable (concat ,variable (progn ,@form))))
690
691 ;;; Concatenate a list of strings, with a separator
692 (defun join (list &optional (separator ""))
693   (cond
694     ((null list)
695      "")
696     ((null (cdr list))
697      (car list))
698     (t
699      (concat (car list)
700              separator
701              (join (cdr list) separator)))))
702
703 (defun join-trailing (list &optional (separator ""))
704   (if (null list)
705       ""
706       (concat (car list) separator (join-trailing (cdr list) separator))))
707
708 (defun mapconcat (func list)
709   (join (mapcar func list)))
710
711 (defun vector-to-list (vector)
712   (let ((list nil)
713         (size (length vector)))
714     (dotimes (i size (reverse list))
715       (push (aref vector i) list))))
716
717 (defun list-to-vector (list)
718   (let ((v (make-array (length list)))
719         (i 0))
720     (dolist (x list v)
721       (aset v i x)
722       (incf i))))
723
724 #+ecmalisp
725 (progn
726   (defun values-list (list)
727     (values-array (list-to-vector list)))
728
729   (defun values (&rest args)
730     (values-list args)))
731
732
733 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
734 ;;; of this function are available, because the Ecmalisp version is
735 ;;; very slow and bootstraping was annoying.
736
737 #+ecmalisp
738 (defun indent (&rest string)
739   (let ((input (join string)))
740     (let ((output "")
741           (index 0)
742           (size (length input)))
743       (when (plusp (length input)) (concatf output "    "))
744       (while (< index size)
745         (let ((str
746                (if (and (char= (char input index) #\newline)
747                         (< index (1- size))
748                         (not (char= (char input (1+ index)) #\newline)))
749                    (concat (string #\newline) "    ")
750                    (string (char input index)))))
751           (concatf output str))
752         (incf index))
753       output)))
754
755 #+common-lisp
756 (defun indent (&rest string)
757   (with-output-to-string (*standard-output*)
758     (with-input-from-string (input (join string))
759       (loop
760          for line = (read-line input nil)
761          while line
762          do (write-string "    ")
763          do (write-line line)))))
764
765 (defun integer-to-string (x)
766   (cond
767     ((zerop x)
768      "0")
769     ((minusp x)
770      (concat "-" (integer-to-string (- 0 x))))
771     (t
772      (let ((digits nil))
773        (while (not (zerop x))
774          (push (mod x 10) digits)
775          (setq x (truncate x 10)))
776        (mapconcat (lambda (x) (string (digit-char x)))
777                   digits)))))
778
779
780 ;;; Wrap X with a Javascript code to convert the result from
781 ;;; Javascript generalized booleans to T or NIL.
782 (defun js!bool (x)
783   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
784
785 ;;; Concatenate the arguments and wrap them with a self-calling
786 ;;; Javascript anonymous function. It is used to make some Javascript
787 ;;; statements valid expressions and provide a private scope as well.
788 ;;; It could be defined as function, but we could do some
789 ;;; preprocessing in the future.
790 (defmacro js!selfcall (&body body)
791   `(concat "(function(){" *newline* (indent ,@body) "})()"))
792
793
794 ;;; Printer
795
796 #+ecmalisp
797 (progn
798   (defun prin1-to-string (form)
799     (cond
800       ((symbolp form)
801        (multiple-value-bind (symbol foundp)
802            (find-symbol (symbol-name form) *package*)
803          (if (and foundp (eq symbol form))
804              (symbol-name form)
805              (let ((package (symbol-package form))
806                    (name (symbol-name form)))
807                (concat (cond
808                          ((null package) "#")
809                          ((eq package (find-package "KEYWORD")) "")
810                          (t (package-name package)))
811                        ":" name)))))
812       ((integerp form) (integer-to-string form))
813       ((stringp form) (concat "\"" (escape-string form) "\""))
814       ((functionp form)
815        (let ((name (oget form "fname")))
816          (if name
817              (concat "#<FUNCTION " name ">")
818              (concat "#<FUNCTION>"))))
819       ((listp form)
820        (concat "("
821                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
822                (let ((last (last form)))
823                  (if (null (cdr last))
824                      (prin1-to-string (car last))
825                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
826                ")"))
827       ((arrayp form)
828        (concat "#" (prin1-to-string (vector-to-list form))))
829       ((packagep form)
830        (concat "#<PACKAGE " (package-name form) ">"))))
831
832   (defun write-line (x)
833     (write-string x)
834     (write-string *newline*)
835     x)
836
837   (defun warn (string)
838     (write-string "WARNING: ")
839     (write-line string))
840
841   (defun print (x)
842     (write-line (prin1-to-string x))
843     x))
844
845
846 ;;;; Reader
847
848 ;;; The Lisp reader, parse strings and return Lisp objects. The main
849 ;;; entry points are `ls-read' and `ls-read-from-string'.
850
851 (defun make-string-stream (string)
852   (cons string 0))
853
854 (defun %peek-char (stream)
855   (and (< (cdr stream) (length (car stream)))
856        (char (car stream) (cdr stream))))
857
858 (defun %read-char (stream)
859   (and (< (cdr stream) (length (car stream)))
860        (prog1 (char (car stream) (cdr stream))
861          (rplacd stream (1+ (cdr stream))))))
862
863 (defun whitespacep (ch)
864   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
865
866 (defun skip-whitespaces (stream)
867   (let (ch)
868     (setq ch (%peek-char stream))
869     (while (and ch (whitespacep ch))
870       (%read-char stream)
871       (setq ch (%peek-char stream)))))
872
873 (defun terminalp (ch)
874   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
875
876 (defun read-until (stream func)
877   (let ((string "")
878         (ch))
879     (setq ch (%peek-char stream))
880     (while (and ch (not (funcall func ch)))
881       (setq string (concat string (string ch)))
882       (%read-char stream)
883       (setq ch (%peek-char stream)))
884     string))
885
886 (defun skip-whitespaces-and-comments (stream)
887   (let (ch)
888     (skip-whitespaces stream)
889     (setq ch (%peek-char stream))
890     (while (and ch (char= ch #\;))
891       (read-until stream (lambda (x) (char= x #\newline)))
892       (skip-whitespaces stream)
893       (setq ch (%peek-char stream)))))
894
895 (defun %read-list (stream)
896   (skip-whitespaces-and-comments stream)
897   (let ((ch (%peek-char stream)))
898     (cond
899       ((null ch)
900        (error "Unspected EOF"))
901       ((char= ch #\))
902        (%read-char stream)
903        nil)
904       ((char= ch #\.)
905        (%read-char stream)
906        (prog1 (ls-read stream)
907          (skip-whitespaces-and-comments stream)
908          (unless (char= (%read-char stream) #\))
909            (error "')' was expected."))))
910       (t
911        (cons (ls-read stream) (%read-list stream))))))
912
913 (defun read-string (stream)
914   (let ((string "")
915         (ch nil))
916     (setq ch (%read-char stream))
917     (while (not (eql ch #\"))
918       (when (null ch)
919         (error "Unexpected EOF"))
920       (when (eql ch #\\)
921         (setq ch (%read-char stream)))
922       (setq string (concat string (string ch)))
923       (setq ch (%read-char stream)))
924     string))
925
926 (defun read-sharp (stream)
927   (%read-char stream)
928   (ecase (%read-char stream)
929     (#\'
930      (list 'function (ls-read stream)))
931     (#\( (list-to-vector (%read-list stream)))
932     (#\: (make-symbol (string-upcase (read-until stream #'terminalp))))
933     (#\\
934      (let ((cname
935             (concat (string (%read-char stream))
936                     (read-until stream #'terminalp))))
937        (cond
938          ((string= cname "space") (char-code #\space))
939          ((string= cname "tab") (char-code #\tab))
940          ((string= cname "newline") (char-code #\newline))
941          (t (char-code (char cname 0))))))
942     (#\+
943      (let ((feature (read-until stream #'terminalp)))
944        (cond
945          ((string= feature "common-lisp")
946           (ls-read stream)              ;ignore
947           (ls-read stream))
948          ((string= feature "ecmalisp")
949           (ls-read stream))
950          (t
951           (error "Unknown reader form.")))))))
952
953 ;;; Parse a string of the form NAME, PACKAGE:NAME or
954 ;;; PACKAGE::NAME and return the name. If the string is of the
955 ;;; form 1) or 3), but the symbol does not exist, it will be created
956 ;;; and interned in that package.
957 (defun read-symbol (string)
958   (let ((size (length string))
959         package name internalp index)
960     (setq index 0)
961     (while (and (< index size)
962                 (not (char= (char string index) #\:)))
963       (incf index))
964     (cond
965       ;; No package prefix
966       ((= index size)
967        (setq name string)
968        (setq package *package*)
969        (setq internalp t))
970       (t
971        ;; Package prefix
972        (if (zerop index)
973            (setq package "KEYWORD")
974            (setq package (string-upcase (subseq string 0 index))))
975        (incf index)
976        (when (char= (char string index) #\:)
977          (setq internalp t)
978          (incf index))
979        (setq name (subseq string index))))
980     ;; Canonalize symbol name and package
981     (setq name (string-upcase name))
982     (setq package (find-package package))
983     ;; TODO: PACKAGE:SYMBOL should signal error if SYMBOL is not an
984     ;; external symbol from PACKAGE.
985     (if (or internalp (eq package (find-package "KEYWORD")))
986         (intern name package)
987         (find-symbol name package))))
988
989
990 (defun !parse-integer (string junk-allow)
991   (block nil
992     (let ((value 0)
993           (index 0)
994           (size (length string))
995           (sign 1))
996       (when (zerop size) (return (values nil 0)))
997       ;; Optional sign
998       (case (char string 0)
999         (#\+ (incf index))
1000         (#\- (setq sign -1)
1001              (incf index)))
1002       ;; First digit
1003       (unless (and (< index size)
1004                    (setq value (digit-char-p (char string index))))
1005         (return (values nil index)))
1006       (incf index)
1007       ;; Other digits
1008       (while (< index size)
1009         (let ((digit (digit-char-p (char string index))))
1010           (unless digit (return))
1011           (setq value (+ (* value 10) digit))
1012           (incf index)))
1013       (if (or junk-allow
1014               (= index size)
1015               (char= (char string index) #\space))
1016           (values (* sign value) index)
1017           (values nil index)))))
1018
1019 #+ecmalisp
1020 (defun parse-integer (string)
1021   (!parse-integer string nil))
1022
1023 (defvar *eof* (gensym))
1024 (defun ls-read (stream)
1025   (skip-whitespaces-and-comments stream)
1026   (let ((ch (%peek-char stream)))
1027     (cond
1028       ((or (null ch) (char= ch #\)))
1029        *eof*)
1030       ((char= ch #\()
1031        (%read-char stream)
1032        (%read-list stream))
1033       ((char= ch #\')
1034        (%read-char stream)
1035        (list 'quote (ls-read stream)))
1036       ((char= ch #\`)
1037        (%read-char stream)
1038        (list 'backquote (ls-read stream)))
1039       ((char= ch #\")
1040        (%read-char stream)
1041        (read-string stream))
1042       ((char= ch #\,)
1043        (%read-char stream)
1044        (if (eql (%peek-char stream) #\@)
1045            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
1046            (list 'unquote (ls-read stream))))
1047       ((char= ch #\#)
1048        (read-sharp stream))
1049       (t
1050        (let ((string (read-until stream #'terminalp)))
1051          (or (values (!parse-integer string nil))
1052              (read-symbol string)))))))
1053
1054 (defun ls-read-from-string (string)
1055   (ls-read (make-string-stream string)))
1056
1057
1058 ;;;; Compiler
1059
1060 ;;; Translate the Lisp code to Javascript. It will compile the special
1061 ;;; forms. Some primitive functions are compiled as special forms
1062 ;;; too. The respective real functions are defined in the target (see
1063 ;;; the beginning of this file) as well as some primitive functions.
1064
1065 ;;; A Form can return a multiple values object calling VALUES, like
1066 ;;; values(arg1, arg2, ...). It will work in any context, as well as
1067 ;;; returning an individual object. However, if the special variable
1068 ;;; `*multiple-value-p*' is NIL, is granted that only the primary
1069 ;;; value will be used, so we can optimize to avoid the VALUES
1070 ;;; function call.
1071 (defvar *multiple-value-p* nil)
1072
1073
1074 (defun make-binding (name type value &optional declarations)
1075   (list name type value declarations))
1076
1077 (defun binding-name (b) (first b))
1078 (defun binding-type (b) (second b))
1079 (defun binding-value (b) (third b))
1080 (defun binding-declarations (b) (fourth b))
1081
1082 (defun set-binding-value (b value)
1083   (rplaca (cddr b) value))
1084
1085 (defun set-binding-declarations (b value)
1086   (rplaca (cdddr b) value))
1087
1088 (defun push-binding-declaration (decl b)
1089   (set-binding-declarations b (cons decl (binding-declarations b))))
1090
1091
1092 (defun make-lexenv ()
1093   (list nil nil nil nil))
1094
1095 (defun copy-lexenv (lexenv)
1096   (copy-list lexenv))
1097
1098 (defun push-to-lexenv (binding lexenv namespace)
1099   (ecase namespace
1100     (variable   (rplaca        lexenv  (cons binding (car lexenv))))
1101     (function   (rplaca   (cdr lexenv) (cons binding (cadr lexenv))))
1102     (block      (rplaca  (cddr lexenv) (cons binding (caddr lexenv))))
1103     (gotag      (rplaca (cdddr lexenv) (cons binding (cadddr lexenv))))))
1104
1105 (defun extend-lexenv (bindings lexenv namespace)
1106   (let ((env (copy-lexenv lexenv)))
1107     (dolist (binding (reverse bindings) env)
1108       (push-to-lexenv binding env namespace))))
1109
1110 (defun lookup-in-lexenv (name lexenv namespace)
1111   (assoc name (ecase namespace
1112                 (variable (first lexenv))
1113                 (function (second lexenv))
1114                 (block (third lexenv))
1115                 (gotag (fourth lexenv)))))
1116
1117 (defvar *environment* (make-lexenv))
1118
1119 (defvar *variable-counter* 0)
1120 (defun gvarname (symbol)
1121   (concat "v" (integer-to-string (incf *variable-counter*))))
1122
1123 (defun translate-variable (symbol)
1124   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
1125
1126 (defun extend-local-env (args)
1127   (let ((new (copy-lexenv *environment*)))
1128     (dolist (symbol args new)
1129       (let ((b (make-binding symbol 'variable (gvarname symbol))))
1130         (push-to-lexenv b new 'variable)))))
1131
1132 ;;; Toplevel compilations
1133 (defvar *toplevel-compilations* nil)
1134
1135 (defun toplevel-compilation (string)
1136   (push string *toplevel-compilations*))
1137
1138 (defun null-or-empty-p (x)
1139   (zerop (length x)))
1140
1141 (defun get-toplevel-compilations ()
1142   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
1143
1144 (defun %compile-defmacro (name lambda)
1145   (toplevel-compilation (ls-compile `',name))
1146   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function)
1147   name)
1148
1149 (defun global-binding (name type namespace)
1150   (or (lookup-in-lexenv name *environment* namespace)
1151       (let ((b (make-binding name type nil)))
1152         (push-to-lexenv b *environment* namespace)
1153         b)))
1154
1155 (defun claimp (symbol namespace claim)
1156   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
1157     (and b (member claim (binding-declarations b)))))
1158
1159 (defun !proclaim (decl)
1160   (case (car decl)
1161     (special
1162      (dolist (name (cdr decl))
1163        (let ((b (global-binding name 'variable 'variable)))
1164          (push-binding-declaration 'special b))))
1165     (notinline
1166      (dolist (name (cdr decl))
1167        (let ((b (global-binding name 'function 'function)))
1168          (push-binding-declaration 'notinline b))))
1169     (constant
1170      (dolist (name (cdr decl))
1171        (let ((b (global-binding name 'variable 'variable)))
1172          (push-binding-declaration 'constant b))))))
1173
1174 #+ecmalisp
1175 (fset 'proclaim #'!proclaim)
1176
1177 ;;; Special forms
1178
1179 (defvar *compilations* nil)
1180
1181 (defmacro define-compilation (name args &body body)
1182   ;; Creates a new primitive `name' with parameters args and
1183   ;; @body. The body can access to the local environment through the
1184   ;; variable *ENVIRONMENT*.
1185   `(push (list ',name (lambda ,args (block ,name ,@body)))
1186          *compilations*))
1187
1188 (define-compilation if (condition true false)
1189   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
1190           " ? " (ls-compile true *multiple-value-p*)
1191           " : " (ls-compile false *multiple-value-p*)
1192           ")"))
1193
1194 (defvar *lambda-list-keywords* '(&optional &rest &key))
1195
1196 (defun list-until-keyword (list)
1197   (if (or (null list) (member (car list) *lambda-list-keywords*))
1198       nil
1199       (cons (car list) (list-until-keyword (cdr list)))))
1200
1201 (defun lambda-list-section (keyword lambda-list)
1202   (list-until-keyword (cdr (member keyword lambda-list))))
1203
1204 (defun lambda-list-required-arguments (lambda-list)
1205   (list-until-keyword lambda-list))
1206
1207 (defun lambda-list-optional-arguments-with-default (lambda-list)
1208   (mapcar #'ensure-list (lambda-list-section '&optional lambda-list)))
1209
1210 (defun lambda-list-optional-arguments (lambda-list)
1211   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
1212
1213 (defun lambda-list-rest-argument (lambda-list)
1214   (let ((rest (lambda-list-section '&rest lambda-list)))
1215     (when (cdr rest)
1216       (error "Bad lambda-list"))
1217     (car rest)))
1218
1219 (defun lambda-list-keyword-arguments-canonical (lambda-list)
1220   (flet ((canonalize (keyarg)
1221            ;; Build a canonical keyword argument descriptor, filling
1222            ;; the optional fields. The result is a list of the form
1223            ;; ((keyword-name var) init-form).
1224            (let* ((arg (ensure-list keyarg))
1225                   (init-form (cadr arg))
1226                   var
1227                   keyword-name)
1228              (if (listp (car arg))
1229                  (setq var (cadr (car arg))
1230                        keyword-name (car (car arg)))
1231                  (setq var (car arg)
1232                        keyword-name (intern (symbol-name (car arg)) "KEYWORD")))
1233              `((,keyword-name ,var) ,init-form))))
1234     (mapcar #'canonalize (lambda-list-section '&key lambda-list))))
1235
1236 (defun lambda-docstring-wrapper (docstring &rest strs)
1237   (if docstring
1238       (js!selfcall
1239         "var func = " (join strs) ";" *newline*
1240         "func.docstring = '" docstring "';" *newline*
1241         "return func;" *newline*)
1242       (join strs)))
1243
1244 (defun lambda-check-argument-count
1245     (n-required-arguments n-optional-arguments rest-p)
1246   ;; Note: Remember that we assume that the number of arguments of a
1247   ;; call is at least 1 (the values argument).
1248   (let ((min (1+ n-required-arguments))
1249         (max (if rest-p 'n/a (+ 1 n-required-arguments n-optional-arguments))))
1250     (block nil
1251       ;; Special case: a positive exact number of arguments.
1252       (when (and (< 1 min) (eql min max))
1253         (return (concat "checkArgs(arguments, " (integer-to-string min) ");" *newline*)))
1254       ;; General case:
1255       (concat
1256        (if (< 1 min)
1257            (concat "checkArgsAtLeast(arguments, " (integer-to-string min) ");" *newline*)
1258            "")
1259        (if (numberp max)
1260            (concat "checkArgsAtMost(arguments, " (integer-to-string max) ");" *newline*)
1261            "")))))
1262
1263 (defun compile-lambda (lambda-list body)
1264   (let ((required-arguments (lambda-list-required-arguments lambda-list))
1265         (optional-arguments (lambda-list-optional-arguments lambda-list))
1266         (rest-argument (lambda-list-rest-argument lambda-list))
1267         documentation)
1268     ;; Get the documentation string for the lambda function
1269     (when (and (stringp (car body))
1270                (not (null (cdr body))))
1271       (setq documentation (car body))
1272       (setq body (cdr body)))
1273     (let ((n-required-arguments (length required-arguments))
1274           (n-optional-arguments (length optional-arguments))
1275           (*environment* (extend-local-env
1276                           (append (ensure-list rest-argument)
1277                                   required-arguments
1278                                   optional-arguments))))
1279       (lambda-docstring-wrapper
1280        documentation
1281        "(function ("
1282        (join (cons "values"
1283                    (mapcar #'translate-variable
1284                            (append required-arguments optional-arguments)))
1285              ",")
1286        "){" *newline*
1287        (indent
1288         ;; Check number of arguments
1289         (lambda-check-argument-count n-required-arguments
1290                                      n-optional-arguments
1291                                      rest-argument)
1292         ;; Optional arguments
1293         (if optional-arguments
1294             (concat "switch(arguments.length-1){" *newline*
1295                     (let ((optional-and-defaults
1296                            (lambda-list-optional-arguments-with-default lambda-list))
1297                           (cases nil)
1298                           (idx 0))
1299                       (progn
1300                         (while (< idx n-optional-arguments)
1301                           (let ((arg (nth idx optional-and-defaults)))
1302                             (push (concat "case "
1303                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1304                                           (translate-variable (car arg))
1305                                           "="
1306                                           (ls-compile (cadr arg))
1307                                           ";" *newline*)
1308                                   cases)
1309                             (incf idx)))
1310                         (push (concat "default: break;" *newline*) cases)
1311                         (join (reverse cases))))
1312                     "}" *newline*)
1313             "")
1314         ;; &rest/&body argument
1315         (if rest-argument
1316             (let ((js!rest (translate-variable rest-argument)))
1317               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1318                       "for (var i = arguments.length-1; i>="
1319                       (integer-to-string (+ 1 n-required-arguments n-optional-arguments))
1320                       "; i--)" *newline*
1321                       (indent js!rest " = "
1322                               "{car: arguments[i], cdr: ") js!rest "};"
1323                       *newline*))
1324             "")
1325         ;; Body
1326         (let ((*multiple-value-p* t)) (ls-compile-block body t)))
1327        "})"))))
1328
1329
1330 (defun setq-pair (var val)
1331   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1332     (if (and (eq (binding-type b) 'variable)
1333              (not (member 'special (binding-declarations b)))
1334              (not (member 'constant (binding-declarations b))))
1335         (concat (binding-value b) " = " (ls-compile val))
1336         (ls-compile `(set ',var ,val)))))
1337
1338 (define-compilation setq (&rest pairs)
1339   (let ((result ""))
1340     (while t
1341       (cond
1342         ((null pairs) (return))
1343         ((null (cdr pairs))
1344          (error "Odd paris in SETQ"))
1345         (t
1346          (concatf result
1347            (concat (setq-pair (car pairs) (cadr pairs))
1348                    (if (null (cddr pairs)) "" ", ")))
1349          (setq pairs (cddr pairs)))))
1350     (concat "(" result ")")))
1351
1352 ;;; FFI Variable accessors
1353 (define-compilation js-vref (var)
1354   var)
1355
1356 (define-compilation js-vset (var val)
1357   (concat "(" var " = " (ls-compile val) ")"))
1358
1359
1360
1361 ;;; Literals
1362 (defun escape-string (string)
1363   (let ((output "")
1364         (index 0)
1365         (size (length string)))
1366     (while (< index size)
1367       (let ((ch (char string index)))
1368         (when (or (char= ch #\") (char= ch #\\))
1369           (setq output (concat output "\\")))
1370         (when (or (char= ch #\newline))
1371           (setq output (concat output "\\"))
1372           (setq ch #\n))
1373         (setq output (concat output (string ch))))
1374       (incf index))
1375     output))
1376
1377
1378 (defvar *literal-symbols* nil)
1379 (defvar *literal-counter* 0)
1380
1381 (defun genlit ()
1382   (concat "l" (integer-to-string (incf *literal-counter*))))
1383
1384 (defun literal (sexp &optional recursive)
1385   (cond
1386     ((integerp sexp) (integer-to-string sexp))
1387     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1388     ((symbolp sexp)
1389      (or (cdr (assoc sexp *literal-symbols*))
1390          (let ((v (genlit))
1391                (s #+common-lisp
1392                  (let ((package (symbol-package sexp)))
1393                    (if (eq package (find-package "KEYWORD"))
1394                        (concat "{name: \"" (escape-string (symbol-name sexp))
1395                                "\", 'package': '" (package-name package) "'}")
1396                        (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")))
1397                  #+ecmalisp
1398                  (let ((package (symbol-package sexp)))
1399                    (if (null package)
1400                        (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1401                        (ls-compile `(intern ,(symbol-name sexp) ,(package-name package)))))))
1402            (push (cons sexp v) *literal-symbols*)
1403            (toplevel-compilation (concat "var " v " = " s))
1404            v)))
1405     ((consp sexp)
1406      (let* ((head (butlast sexp))
1407             (tail (last sexp))
1408             (c (concat "QIList("
1409                        (join-trailing (mapcar (lambda (x) (literal x t)) head) ",")
1410                        (literal (car tail) t)
1411                        ","
1412                        (literal (cdr tail) t)
1413                        ")")))
1414        (if recursive
1415            c
1416            (let ((v (genlit)))
1417              (toplevel-compilation (concat "var " v " = " c))
1418              v))))
1419     ((arrayp sexp)
1420      (let ((elements (vector-to-list sexp)))
1421        (let ((c (concat "[" (join (mapcar #'literal elements) ", ") "]")))
1422          (if recursive
1423              c
1424              (let ((v (genlit)))
1425                (toplevel-compilation (concat "var " v " = " c))
1426                v)))))))
1427
1428 (define-compilation quote (sexp)
1429   (literal sexp))
1430
1431 (define-compilation %while (pred &rest body)
1432   (js!selfcall
1433     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1434     (indent (ls-compile-block body))
1435     "}"
1436     "return " (ls-compile nil) ";" *newline*))
1437
1438 (define-compilation function (x)
1439   (cond
1440     ((and (listp x) (eq (car x) 'lambda))
1441      (compile-lambda (cadr x) (cddr x)))
1442     ((symbolp x)
1443      (let ((b (lookup-in-lexenv x *environment* 'function)))
1444        (if b
1445            (binding-value b)
1446            (ls-compile `(symbol-function ',x)))))))
1447
1448
1449 (defun make-function-binding (fname)
1450   (make-binding fname 'function (gvarname fname)))
1451
1452 (defun compile-function-definition (list)
1453   (compile-lambda (car list) (cdr list)))
1454
1455 (defun translate-function (name)
1456   (let ((b (lookup-in-lexenv name *environment* 'function)))
1457     (binding-value b)))
1458
1459 (define-compilation flet (definitions &rest body)
1460   (let* ((fnames (mapcar #'car definitions))
1461          (fbody  (mapcar #'cdr definitions))
1462          (cfuncs (mapcar #'compile-function-definition fbody))
1463          (*environment*
1464           (extend-lexenv (mapcar #'make-function-binding fnames)
1465                          *environment*
1466                          'function)))
1467     (concat "(function("
1468             (join (mapcar #'translate-function fnames) ",")
1469             "){" *newline*
1470             (let ((body (ls-compile-block body t)))
1471               (indent body))
1472             "})(" (join cfuncs ",") ")")))
1473
1474 (define-compilation labels (definitions &rest body)
1475   (let* ((fnames (mapcar #'car definitions))
1476          (*environment*
1477           (extend-lexenv (mapcar #'make-function-binding fnames)
1478                          *environment*
1479                          'function)))
1480     (js!selfcall
1481       (mapconcat (lambda (func)
1482                    (concat "var " (translate-function (car func))
1483                            " = " (compile-lambda (cadr func) (cddr func))
1484                            ";" *newline*))
1485                  definitions)
1486       (ls-compile-block body t))))
1487
1488
1489
1490 (defvar *compiling-file* nil)
1491 (define-compilation eval-when-compile (&rest body)
1492   (if *compiling-file*
1493       (progn
1494         (eval (cons 'progn body))
1495         nil)
1496       (ls-compile `(progn ,@body))))
1497
1498 (defmacro define-transformation (name args form)
1499   `(define-compilation ,name ,args
1500      (ls-compile ,form)))
1501
1502 (define-compilation progn (&rest body)
1503   (if (null (cdr body))
1504       (ls-compile (car body) *multiple-value-p*)
1505       (js!selfcall (ls-compile-block body t))))
1506
1507 (defun special-variable-p (x)
1508   (and (claimp x 'variable 'special) t))
1509
1510 ;;; Wrap CODE to restore the symbol values of the dynamic
1511 ;;; bindings. BINDINGS is a list of pairs of the form
1512 ;;; (SYMBOL . PLACE),  where PLACE is a Javascript variable
1513 ;;; name to initialize the symbol value and where to stored
1514 ;;; the old value.
1515 (defun let-binding-wrapper (bindings body)
1516   (when (null bindings)
1517     (return-from let-binding-wrapper body))
1518   (concat
1519    "try {" *newline*
1520    (indent "var tmp;" *newline*
1521            (mapconcat
1522             (lambda (b)
1523               (let ((s (ls-compile `(quote ,(car b)))))
1524                 (concat "tmp = " s ".value;" *newline*
1525                         s ".value = " (cdr b) ";" *newline*
1526                         (cdr b) " = tmp;" *newline*)))
1527             bindings)
1528            body *newline*)
1529    "}" *newline*
1530    "finally {"  *newline*
1531    (indent
1532     (mapconcat (lambda (b)
1533                  (let ((s (ls-compile `(quote ,(car b)))))
1534                    (concat s ".value" " = " (cdr b) ";" *newline*)))
1535                bindings))
1536    "}" *newline*))
1537
1538 (define-compilation let (bindings &rest body)
1539   (let* ((bindings (mapcar #'ensure-list bindings))
1540          (variables (mapcar #'first bindings))
1541          (cvalues (mapcar #'ls-compile (mapcar #'second bindings)))
1542          (*environment* (extend-local-env (remove-if #'special-variable-p variables)))
1543          (dynamic-bindings))
1544     (concat "(function("
1545             (join (mapcar (lambda (x)
1546                             (if (special-variable-p x)
1547                                 (let ((v (gvarname x)))
1548                                   (push (cons x v) dynamic-bindings)
1549                                   v)
1550                                 (translate-variable x)))
1551                           variables)
1552                   ",")
1553             "){" *newline*
1554             (let ((body (ls-compile-block body t)))
1555               (indent (let-binding-wrapper dynamic-bindings body)))
1556             "})(" (join cvalues ",") ")")))
1557
1558
1559 ;;; Return the code to initialize BINDING, and push it extending the
1560 ;;; current lexical environment if the variable is not special.
1561 (defun let*-initialize-value (binding)
1562   (let ((var (first binding))
1563         (value (second binding)))
1564     (if (special-variable-p var)
1565         (concat (ls-compile `(setq ,var ,value)) ";" *newline*)
1566         (let* ((v (gvarname var))
1567                (b (make-binding var 'variable v)))
1568           (prog1 (concat "var " v " = " (ls-compile value) ";" *newline*)
1569             (push-to-lexenv b *environment* 'variable))))))
1570
1571 ;;; Wrap BODY to restore the symbol values of SYMBOLS after body. It
1572 ;;; DOES NOT generate code to initialize the value of the symbols,
1573 ;;; unlike let-binding-wrapper.
1574 (defun let*-binding-wrapper (symbols body)
1575   (when (null symbols)
1576     (return-from let*-binding-wrapper body))
1577   (let ((store (mapcar (lambda (s) (cons s (gvarname s)))
1578                        (remove-if-not #'special-variable-p symbols))))
1579     (concat
1580      "try {" *newline*
1581      (indent
1582       (mapconcat (lambda (b)
1583                    (let ((s (ls-compile `(quote ,(car b)))))
1584                      (concat "var " (cdr b) " = " s ".value;" *newline*)))
1585                  store)
1586       body)
1587      "}" *newline*
1588      "finally {" *newline*
1589      (indent
1590       (mapconcat (lambda (b)
1591                    (let ((s (ls-compile `(quote ,(car b)))))
1592                      (concat s ".value" " = " (cdr b) ";" *newline*)))
1593                  store))
1594      "}" *newline*)))
1595
1596 (define-compilation let* (bindings &rest body)
1597   (let ((bindings (mapcar #'ensure-list bindings))
1598         (*environment* (copy-lexenv *environment*)))
1599     (js!selfcall
1600       (let ((specials (remove-if-not #'special-variable-p (mapcar #'first bindings)))
1601             (body (concat (mapconcat #'let*-initialize-value bindings)
1602                           (ls-compile-block body t))))
1603         (let*-binding-wrapper specials body)))))
1604
1605
1606 (defvar *block-counter* 0)
1607
1608 (define-compilation block (name &rest body)
1609   (let* ((tr (integer-to-string (incf *block-counter*)))
1610          (b (make-binding name 'block tr)))
1611     (when *multiple-value-p*
1612       (push-binding-declaration 'multiple-value b))
1613     (let* ((*environment* (extend-lexenv (list b) *environment* 'block))
1614            (cbody (ls-compile-block body t)))
1615       (if (member 'used (binding-declarations b))
1616           (js!selfcall
1617             "try {" *newline*
1618             (indent cbody)
1619             "}" *newline*
1620             "catch (cf){" *newline*
1621             "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1622             (if *multiple-value-p*
1623                 "        return values.apply(this, forcemv(cf.values));"
1624                 "        return cf.values;")
1625             *newline*
1626             "    else" *newline*
1627             "        throw cf;" *newline*
1628             "}" *newline*)
1629           (js!selfcall cbody)))))
1630
1631 (define-compilation return-from (name &optional value)
1632   (let* ((b (lookup-in-lexenv name *environment* 'block))
1633          (multiple-value-p (member 'multiple-value (binding-declarations b))))
1634     (when (null b)
1635       (error (concat "Unknown block `" (symbol-name name) "'.")))
1636     (push-binding-declaration 'used b)
1637     (js!selfcall
1638       (if multiple-value-p
1639           (concat "var values = mv;" *newline*)
1640           "")
1641       "throw ({"
1642       "type: 'block', "
1643       "id: " (binding-value b) ", "
1644       "values: " (ls-compile value multiple-value-p) ", "
1645       "message: 'Return from unknown block " (symbol-name name) ".'"
1646       "})")))
1647
1648 (define-compilation catch (id &rest body)
1649   (js!selfcall
1650     "var id = " (ls-compile id) ";" *newline*
1651     "try {" *newline*
1652     (indent (ls-compile-block body t)) *newline*
1653     "}" *newline*
1654     "catch (cf){" *newline*
1655     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1656     (if *multiple-value-p*
1657         "        return values.apply(this, forcemv(cf.values));"
1658         "        return pv.apply(this, forcemv(cf.values));")
1659     *newline*
1660     "    else" *newline*
1661     "        throw cf;" *newline*
1662     "}" *newline*))
1663
1664 (define-compilation throw (id value)
1665   (js!selfcall
1666     "var values = mv;" *newline*
1667     "throw ({"
1668     "type: 'catch', "
1669     "id: " (ls-compile id) ", "
1670     "values: " (ls-compile value t) ", "
1671     "message: 'Throw uncatched.'"
1672     "})"))
1673
1674
1675 (defvar *tagbody-counter* 0)
1676 (defvar *go-tag-counter* 0)
1677
1678 (defun go-tag-p (x)
1679   (or (integerp x) (symbolp x)))
1680
1681 (defun declare-tagbody-tags (tbidx body)
1682   (let ((bindings
1683          (mapcar (lambda (label)
1684                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1685                      (make-binding label 'gotag (list tbidx tagidx))))
1686                  (remove-if-not #'go-tag-p body))))
1687     (extend-lexenv bindings *environment* 'gotag)))
1688
1689 (define-compilation tagbody (&rest body)
1690   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1691   ;; because 1) it is easy and 2) many built-in forms expand to a
1692   ;; implicit tagbody, so we save some space.
1693   (unless (some #'go-tag-p body)
1694     (return-from tagbody (ls-compile `(progn ,@body nil))))
1695   ;; The translation assumes the first form in BODY is a label
1696   (unless (go-tag-p (car body))
1697     (push (gensym "START") body))
1698   ;; Tagbody compilation
1699   (let ((tbidx (integer-to-string *tagbody-counter*)))
1700     (let ((*environment* (declare-tagbody-tags tbidx body))
1701           initag)
1702       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1703         (setq initag (second (binding-value b))))
1704       (js!selfcall
1705         "var tagbody_" tbidx " = " initag ";" *newline*
1706         "tbloop:" *newline*
1707         "while (true) {" *newline*
1708         (indent "try {" *newline*
1709                 (indent (let ((content ""))
1710                           (concat "switch(tagbody_" tbidx "){" *newline*
1711                                   "case " initag ":" *newline*
1712                                   (dolist (form (cdr body) content)
1713                                     (concatf content
1714                                       (if (not (go-tag-p form))
1715                                           (indent (ls-compile form) ";" *newline*)
1716                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1717                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1718                                   "default:" *newline*
1719                                   "    break tbloop;" *newline*
1720                                   "}" *newline*)))
1721                 "}" *newline*
1722                 "catch (jump) {" *newline*
1723                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1724                 "        tagbody_" tbidx " = jump.label;" *newline*
1725                 "    else" *newline*
1726                 "        throw(jump);" *newline*
1727                 "}" *newline*)
1728         "}" *newline*
1729         "return " (ls-compile nil) ";" *newline*))))
1730
1731 (define-compilation go (label)
1732   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1733         (n (cond
1734              ((symbolp label) (symbol-name label))
1735              ((integerp label) (integer-to-string label)))))
1736     (if b
1737         (js!selfcall
1738           "throw ({"
1739           "type: 'tagbody', "
1740           "id: " (first (binding-value b)) ", "
1741           "label: " (second (binding-value b)) ", "
1742           "message: 'Attempt to GO to non-existing tag " n "'"
1743           "})" *newline*)
1744         (error (concat "Unknown tag `" n "'.")))))
1745
1746 (define-compilation unwind-protect (form &rest clean-up)
1747   (js!selfcall
1748     "var ret = " (ls-compile nil) ";" *newline*
1749     "try {" *newline*
1750     (indent "ret = " (ls-compile form) ";" *newline*)
1751     "} finally {" *newline*
1752     (indent (ls-compile-block clean-up))
1753     "}" *newline*
1754     "return ret;" *newline*))
1755
1756 (define-compilation multiple-value-call (func-form &rest forms)
1757   (js!selfcall
1758     "var func = " (ls-compile func-form) ";" *newline*
1759     "var args = [" (if *multiple-value-p* "values" "pv") "];" *newline*
1760     "return "
1761     (js!selfcall
1762       "var values = mv;" *newline*
1763       "var vs;" *newline*
1764       (mapconcat (lambda (form)
1765                    (concat "vs = " (ls-compile form t) ";" *newline*
1766                            "if (typeof vs === 'object' && 'multiple-value' in vs)" *newline*
1767                            (indent "args = args.concat(vs);" *newline*)
1768                            "else" *newline*
1769                            (indent "args.push(vs);" *newline*)))
1770                  forms)
1771       "return func.apply(window, args);" *newline*) ";" *newline*))
1772
1773 (define-compilation multiple-value-prog1 (first-form &rest forms)
1774   (js!selfcall
1775     "var args = " (ls-compile first-form *multiple-value-p*) ";" *newline*
1776     (ls-compile-block forms)
1777     "return args;" *newline*))
1778
1779
1780
1781 ;;; A little backquote implementation without optimizations of any
1782 ;;; kind for ecmalisp.
1783 (defun backquote-expand-1 (form)
1784   (cond
1785     ((symbolp form)
1786      (list 'quote form))
1787     ((atom form)
1788      form)
1789     ((eq (car form) 'unquote)
1790      (car form))
1791     ((eq (car form) 'backquote)
1792      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1793     (t
1794      (cons 'append
1795            (mapcar (lambda (s)
1796                      (cond
1797                        ((and (listp s) (eq (car s) 'unquote))
1798                         (list 'list (cadr s)))
1799                        ((and (listp s) (eq (car s) 'unquote-splicing))
1800                         (cadr s))
1801                        (t
1802                         (list 'list (backquote-expand-1 s)))))
1803                    form)))))
1804
1805 (defun backquote-expand (form)
1806   (if (and (listp form) (eq (car form) 'backquote))
1807       (backquote-expand-1 (cadr form))
1808       form))
1809
1810 (defmacro backquote (form)
1811   (backquote-expand-1 form))
1812
1813 (define-transformation backquote (form)
1814   (backquote-expand-1 form))
1815
1816 ;;; Primitives
1817
1818 (defvar *builtins* nil)
1819
1820 (defmacro define-raw-builtin (name args &body body)
1821   ;; Creates a new primitive function `name' with parameters args and
1822   ;; @body. The body can access to the local environment through the
1823   ;; variable *ENVIRONMENT*.
1824   `(push (list ',name (lambda ,args (block ,name ,@body)))
1825          *builtins*))
1826
1827 (defmacro define-builtin (name args &body body)
1828   `(progn
1829      (define-raw-builtin ,name ,args
1830        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1831          ,@body))))
1832
1833 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1834 (defmacro type-check (decls &body body)
1835   `(js!selfcall
1836      ,@(mapcar (lambda (decl)
1837                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1838                  decls)
1839      ,@(mapcar (lambda (decl)
1840                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1841                           (indent "throw 'The value ' + "
1842                                   ,(first decl)
1843                                   " + ' is not a type "
1844                                   ,(second decl)
1845                                   ".';"
1846                                   *newline*)))
1847                decls)
1848      (concat "return " (progn ,@body) ";" *newline*)))
1849
1850 ;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
1851 ;;; a variable which holds a list of forms. It will compile them and
1852 ;;; store the result in some Javascript variables. BODY is evaluated
1853 ;;; with ARGS bound to the list of these variables to generate the
1854 ;;; code which performs the transformation on these variables.
1855
1856 (defun variable-arity-call (args function)
1857   (unless (consp args)
1858     (error "ARGS must be a non-empty list"))
1859   (let ((counter 0)
1860         (variables '())
1861         (prelude ""))
1862     (dolist (x args)
1863       (let ((v (concat "x" (integer-to-string (incf counter)))))
1864         (push v variables)
1865         (concatf prelude
1866                  (concat "var " v " = " (ls-compile x) ";" *newline*
1867                          "if (typeof " v " !== 'number') throw 'Not a number!';"
1868                          *newline*))))
1869     (js!selfcall prelude (funcall function (reverse variables)))))
1870
1871
1872 (defmacro variable-arity (args &body body)
1873   (unless (symbolp args)
1874     (error "Bad usage of VARIABLE-ARITY, you must pass a symbol"))
1875   `(variable-arity-call ,args
1876                         (lambda (,args)
1877                           (concat "return " ,@body ";" *newline*))))
1878
1879 (defun num-op-num (x op y)
1880   (type-check (("x" "number" x) ("y" "number" y))
1881     (concat "x" op "y")))
1882
1883 (define-raw-builtin + (&rest numbers)
1884   (if (null numbers)
1885       "0"
1886       (variable-arity numbers
1887         (join numbers "+"))))
1888
1889 (define-raw-builtin - (x &rest others)
1890   (let ((args (cons x others)))
1891     (variable-arity args
1892       (if (null others)
1893           (concat "-" (car args))
1894           (join args "-")))))
1895
1896 (define-raw-builtin * (&rest numbers)
1897   (if (null numbers)
1898       "1"
1899       (variable-arity numbers
1900         (join numbers "*"))))
1901
1902 (define-raw-builtin / (x &rest others)
1903   (let ((args (cons x others)))
1904     (variable-arity args
1905       (if (null others)
1906           (concat "1 /" (car args))
1907           (join args "/")))))
1908
1909 (define-builtin mod (x y) (num-op-num x "%" y))
1910
1911
1912 (defun comparison-conjuntion (vars op)
1913   (cond
1914     ((null (cdr vars))
1915      "true")
1916     ((null (cddr vars))
1917      (concat (car vars) op (cadr vars)))
1918     (t
1919      (concat (car vars) op (cadr vars)
1920              " && "
1921              (comparison-conjuntion (cdr vars) op)))))
1922
1923 (defmacro define-builtin-comparison (op sym)
1924   `(define-raw-builtin ,op (x &rest args)
1925      (let ((args (cons x args)))
1926        (variable-arity args
1927          (js!bool (comparison-conjuntion args ,sym))))))
1928
1929 (define-builtin-comparison > ">")
1930 (define-builtin-comparison < "<")
1931 (define-builtin-comparison >= ">=")
1932 (define-builtin-comparison <= "<=")
1933 (define-builtin-comparison = "==")
1934
1935 (define-builtin numberp (x)
1936   (js!bool (concat "(typeof (" x ") == \"number\")")))
1937
1938 (define-builtin floor (x)
1939   (type-check (("x" "number" x))
1940     "Math.floor(x)"))
1941
1942 (define-builtin cons (x y)
1943   (concat "({car: " x ", cdr: " y "})"))
1944
1945 (define-builtin consp (x)
1946   (js!bool
1947    (js!selfcall
1948      "var tmp = " x ";" *newline*
1949      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1950
1951 (define-builtin car (x)
1952   (js!selfcall
1953     "var tmp = " x ";" *newline*
1954     "return tmp === " (ls-compile nil)
1955     "? " (ls-compile nil)
1956     ": tmp.car;" *newline*))
1957
1958 (define-builtin cdr (x)
1959   (js!selfcall
1960     "var tmp = " x ";" *newline*
1961     "return tmp === " (ls-compile nil) "? "
1962     (ls-compile nil)
1963     ": tmp.cdr;" *newline*))
1964
1965 (define-builtin rplaca (x new)
1966   (type-check (("x" "object" x))
1967     (concat "(x.car = " new ", x)")))
1968
1969 (define-builtin rplacd (x new)
1970   (type-check (("x" "object" x))
1971     (concat "(x.cdr = " new ", x)")))
1972
1973 (define-builtin symbolp (x)
1974   (js!bool
1975    (js!selfcall
1976      "var tmp = " x ";" *newline*
1977      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1978
1979 (define-builtin make-symbol (name)
1980   (type-check (("name" "string" name))
1981     "({name: name})"))
1982
1983 (define-builtin symbol-name (x)
1984   (concat "(" x ").name"))
1985
1986 (define-builtin set (symbol value)
1987   (concat "(" symbol ").value = " value))
1988
1989 (define-builtin fset (symbol value)
1990   (concat "(" symbol ").fvalue = " value))
1991
1992 (define-builtin boundp (x)
1993   (js!bool (concat "(" x ".value !== undefined)")))
1994
1995 (define-builtin symbol-value (x)
1996   (js!selfcall
1997     "var symbol = " x ";" *newline*
1998     "var value = symbol.value;" *newline*
1999     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
2000     "return value;" *newline*))
2001
2002 (define-builtin symbol-function (x)
2003   (js!selfcall
2004     "var symbol = " x ";" *newline*
2005     "var func = symbol.fvalue;" *newline*
2006     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
2007     "return func;" *newline*))
2008
2009 (define-builtin symbol-plist (x)
2010   (concat "((" x ").plist || " (ls-compile nil) ")"))
2011
2012 (define-builtin lambda-code (x)
2013   (concat "(" x ").toString()"))
2014
2015 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
2016 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
2017
2018 (define-builtin char-to-string (x)
2019   (type-check (("x" "number" x))
2020     "String.fromCharCode(x)"))
2021
2022 (define-builtin stringp (x)
2023   (js!bool (concat "(typeof(" x ") == \"string\")")))
2024
2025 (define-builtin string-upcase (x)
2026   (type-check (("x" "string" x))
2027     "x.toUpperCase()"))
2028
2029 (define-builtin string-length (x)
2030   (type-check (("x" "string" x))
2031     "x.length"))
2032
2033 (define-raw-builtin slice (string a &optional b)
2034   (js!selfcall
2035     "var str = " (ls-compile string) ";" *newline*
2036     "var a = " (ls-compile a) ";" *newline*
2037     "var b;" *newline*
2038     (if b
2039         (concat "b = " (ls-compile b) ";" *newline*)
2040         "")
2041     "return str.slice(a,b);" *newline*))
2042
2043 (define-builtin char (string index)
2044   (type-check (("string" "string" string)
2045                ("index" "number" index))
2046     "string.charCodeAt(index)"))
2047
2048 (define-builtin concat-two (string1 string2)
2049   (type-check (("string1" "string" string1)
2050                ("string2" "string" string2))
2051     "string1.concat(string2)"))
2052
2053 (define-raw-builtin funcall (func &rest args)
2054   (concat "(" (ls-compile func) ")("
2055           (join (cons (if *multiple-value-p* "values" "pv")
2056                       (mapcar #'ls-compile args))
2057                 ", ")
2058           ")"))
2059
2060 (define-raw-builtin apply (func &rest args)
2061   (if (null args)
2062       (concat "(" (ls-compile func) ")()")
2063       (let ((args (butlast args))
2064             (last (car (last args))))
2065         (js!selfcall
2066           "var f = " (ls-compile func) ";" *newline*
2067           "var args = [" (join (cons (if *multiple-value-p* "values" "pv")
2068                                      (mapcar #'ls-compile args))
2069                                ", ")
2070           "];" *newline*
2071           "var tail = (" (ls-compile last) ");" *newline*
2072           "while (tail != " (ls-compile nil) "){" *newline*
2073           "    args.push(tail.car);" *newline*
2074           "    tail = tail.cdr;" *newline*
2075           "}" *newline*
2076           "return f.apply(this, args);" *newline*))))
2077
2078 (define-builtin js-eval (string)
2079   (type-check (("string" "string" string))
2080     (if *multiple-value-p*
2081         (js!selfcall
2082           "var v = eval.apply(window, [string]);" *newline*
2083           "if (typeof v !== 'object' || !('multiple-value' in v)){" *newline*
2084           (indent "v = [v];" *newline*
2085                   "v['multiple-value'] = true;" *newline*)
2086           "}" *newline*
2087           "return values.apply(this, v);" *newline*)
2088         "eval.apply(window, [string])")))
2089
2090 (define-builtin error (string)
2091   (js!selfcall "throw " string ";" *newline*))
2092
2093 (define-builtin new () "{}")
2094
2095 (define-builtin objectp (x)
2096   (js!bool (concat "(typeof (" x ") === 'object')")))
2097
2098 (define-builtin oget (object key)
2099   (js!selfcall
2100     "var tmp = " "(" object ")[" key "];" *newline*
2101     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
2102
2103 (define-builtin oset (object key value)
2104   (concat "((" object ")[" key "] = " value ")"))
2105
2106 (define-builtin in (key object)
2107   (js!bool (concat "((" key ") in (" object "))")))
2108
2109 (define-builtin functionp (x)
2110   (js!bool (concat "(typeof " x " == 'function')")))
2111
2112 (define-builtin write-string (x)
2113   (type-check (("x" "string" x))
2114     "lisp.write(x)"))
2115
2116 (define-builtin make-array (n)
2117   (js!selfcall
2118     "var r = [];" *newline*
2119     "for (var i = 0; i < " n "; i++)" *newline*
2120     (indent "r.push(" (ls-compile nil) ");" *newline*)
2121     "return r;" *newline*))
2122
2123 (define-builtin arrayp (x)
2124   (js!bool
2125    (js!selfcall
2126      "var x = " x ";" *newline*
2127      "return typeof x === 'object' && 'length' in x;")))
2128
2129 (define-builtin aref (array n)
2130   (js!selfcall
2131     "var x = " "(" array ")[" n "];" *newline*
2132     "if (x === undefined) throw 'Out of range';" *newline*
2133     "return x;" *newline*))
2134
2135 (define-builtin aset (array n value)
2136   (js!selfcall
2137     "var x = " array ";" *newline*
2138     "var i = " n ";" *newline*
2139     "if (i < 0 || i >= x.length) throw 'Out of range';" *newline*
2140     "return x[i] = " value ";" *newline*))
2141
2142 (define-builtin get-unix-time ()
2143   (concat "(Math.round(new Date() / 1000))"))
2144
2145 (define-builtin values-array (array)
2146   (if *multiple-value-p*
2147       (concat "values.apply(this, " array ")")
2148       (concat "pv.apply(this, " array ")")))
2149
2150 (define-raw-builtin values (&rest args)
2151   (if *multiple-value-p*
2152       (concat "values(" (join (mapcar #'ls-compile args) ", ") ")")
2153       (concat "pv(" (join (mapcar #'ls-compile args) ", ") ")")))
2154
2155 (defun macro (x)
2156   (and (symbolp x)
2157        (let ((b (lookup-in-lexenv x *environment* 'function)))
2158          (and (eq (binding-type b) 'macro)
2159               b))))
2160
2161 (defun ls-macroexpand-1 (form)
2162   (let ((macro-binding (macro (car form))))
2163     (if macro-binding
2164         (let ((expander (binding-value macro-binding)))
2165           (when (listp expander)
2166             (let ((compiled (eval expander)))
2167               ;; The list representation are useful while
2168               ;; bootstrapping, as we can dump the definition of the
2169               ;; macros easily, but they are slow because we have to
2170               ;; evaluate them and compile them now and again. So, let
2171               ;; us replace the list representation version of the
2172               ;; function with the compiled one.
2173               ;;
2174               #+ecmalisp (set-binding-value macro-binding compiled)
2175               (setq expander compiled)))
2176           (apply expander (cdr form)))
2177         form)))
2178
2179 (defun compile-funcall (function args)
2180   (let* ((values-funcs (if *multiple-value-p* "values" "pv"))
2181          (arglist (concat "(" (join (cons values-funcs (mapcar #'ls-compile args)) ", ") ")")))
2182     (cond
2183       ((translate-function function)
2184        (concat (translate-function function) arglist))
2185       ((and (symbolp function)
2186             #+ecmalisp (eq (symbol-package function) (find-package "COMMON-LISP"))
2187             #+common-lisp t)
2188        (concat (ls-compile `',function) ".fvalue" arglist))
2189       (t
2190        (concat (ls-compile `#',function) arglist)))))
2191
2192 (defun ls-compile-block (sexps &optional return-last-p)
2193   (if return-last-p
2194       (concat (ls-compile-block (butlast sexps))
2195               "return " (ls-compile (car (last sexps)) *multiple-value-p*) ";")
2196       (join-trailing
2197        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
2198        (concat ";" *newline*))))
2199
2200 (defun ls-compile (sexp &optional multiple-value-p)
2201   (let ((*multiple-value-p* multiple-value-p))
2202     (cond
2203       ((symbolp sexp)
2204        (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
2205          (cond
2206            ((and b (not (member 'special (binding-declarations b))))
2207             (binding-value b))
2208            ((or (keywordp sexp)
2209                 (member 'constant (binding-declarations b)))
2210             (concat (ls-compile `',sexp) ".value"))
2211            (t
2212             (ls-compile `(symbol-value ',sexp))))))
2213       ((integerp sexp) (integer-to-string sexp))
2214       ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
2215       ((arrayp sexp) (literal sexp))
2216       ((listp sexp)
2217        (let ((name (car sexp))
2218              (args (cdr sexp)))
2219          (cond
2220            ;; Special forms
2221            ((assoc name *compilations*)
2222             (let ((comp (second (assoc name *compilations*))))
2223               (apply comp args)))
2224            ;; Built-in functions
2225            ((and (assoc name *builtins*)
2226                  (not (claimp name 'function 'notinline)))
2227             (let ((comp (second (assoc name *builtins*))))
2228               (apply comp args)))
2229            (t
2230             (if (macro name)
2231                 (ls-compile (ls-macroexpand-1 sexp) multiple-value-p)
2232                 (compile-funcall name args))))))
2233       (t
2234        (error "How should I compile this?")))))
2235
2236 (defun ls-compile-toplevel (sexp &optional multiple-value-p)
2237   (let ((*toplevel-compilations* nil))
2238     (cond
2239       ((and (consp sexp) (eq (car sexp) 'progn))
2240        (let ((subs (mapcar (lambda (s)
2241                              (ls-compile-toplevel s t))
2242                            (cdr sexp))))
2243          (join (remove-if #'null-or-empty-p subs))))
2244       (t
2245        (let ((code (ls-compile sexp multiple-value-p)))
2246          (concat (join-trailing (get-toplevel-compilations)
2247                                 (concat ";" *newline*))
2248                  (if code
2249                      (concat code ";" *newline*)
2250                      "")))))))
2251
2252
2253 ;;; Once we have the compiler, we define the runtime environment and
2254 ;;; interactive development (eval), which works calling the compiler
2255 ;;; and evaluating the Javascript result globally.
2256
2257 #+ecmalisp
2258 (progn
2259   (defun eval (x)
2260     (js-eval (ls-compile-toplevel x t)))
2261
2262   (export '(&rest &optional &body * *gensym-counter* *package* + - /
2263             1+ 1- < <= = = > >= and append apply aref arrayp aset
2264             assoc atom block boundp boundp butlast caar cadddr caddr
2265             cadr car car case catch cdar cdddr cddr cdr cdr char
2266             char-code char= code-char cond cons consp constantly
2267             copy-list decf declaim defparameter defun defmacro defvar
2268             digit-char digit-char-p disassemble do do* documentation
2269             dolist dotimes ecase eq eql equal error eval every export
2270             fdefinition find-package find-symbol first flet fourth
2271             fset funcall function functionp gensym get-universal-time
2272             go identity if in-package incf integerp integerp intern
2273             keywordp labels lambda last length let let*
2274             list-all-packages list listp make-array make-package
2275             make-symbol mapcar member minusp mod multiple-value-bind
2276             multiple-value-call multiple-value-list
2277             multiple-value-prog1 nil not nth nthcdr null numberp or
2278             package-name package-use-list packagep parse-integer plusp
2279             prin1-to-string print proclaim prog1 prog2 progn psetq
2280             push quote remove remove-if remove-if-not return
2281             return-from revappend reverse rplaca rplacd second set
2282             setq some string-upcase string string= stringp subseq
2283             symbol-function symbol-name symbol-package symbol-plist
2284             symbol-value symbolp t tagbody third throw truncate unless
2285             unwind-protect values values-list variable warn when
2286             write-line write-string zerop))
2287
2288   (setq *package* *user-package*)
2289
2290   (js-eval "var lisp")
2291   (js-vset "lisp" (new))
2292   (js-vset "lisp.read" #'ls-read-from-string)
2293   (js-vset "lisp.print" #'prin1-to-string)
2294   (js-vset "lisp.eval" #'eval)
2295   (js-vset "lisp.compile" (lambda (s) (ls-compile-toplevel s t)))
2296   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
2297   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str) t)))
2298
2299   ;; Set the initial global environment to be equal to the host global
2300   ;; environment at this point of the compilation.
2301   (eval-when-compile
2302     (toplevel-compilation
2303      (ls-compile
2304       `(progn
2305          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
2306                    *literal-symbols*)
2307          (setq *literal-symbols* ',*literal-symbols*)
2308          (setq *environment* ',*environment*)
2309          (setq *variable-counter* ,*variable-counter*)
2310          (setq *gensym-counter* ,*gensym-counter*)
2311          (setq *block-counter* ,*block-counter*)))))
2312
2313   (eval-when-compile
2314     (toplevel-compilation
2315      (ls-compile
2316       `(setq *literal-counter* ,*literal-counter*)))))
2317
2318
2319 ;;; Finally, we provide a couple of functions to easily bootstrap
2320 ;;; this. It just calls the compiler with this file as input.
2321
2322 #+common-lisp
2323 (progn
2324   (defun read-whole-file (filename)
2325     (with-open-file (in filename)
2326       (let ((seq (make-array (file-length in) :element-type 'character)))
2327         (read-sequence seq in)
2328         seq)))
2329
2330   (defun ls-compile-file (filename output)
2331     (let ((*compiling-file* t))
2332       (with-open-file (out output :direction :output :if-exists :supersede)
2333         (write-string (read-whole-file "prelude.js") out)
2334         (let* ((source (read-whole-file filename))
2335                (in (make-string-stream source)))
2336           (loop
2337              for x = (ls-read in)
2338              until (eq x *eof*)
2339              for compilation = (ls-compile-toplevel x)
2340              when (plusp (length compilation))
2341              do (write-string compilation out))))))
2342
2343   (defun bootstrap ()
2344     (setq *environment* (make-lexenv))
2345     (setq *literal-symbols* nil)
2346     (setq *variable-counter* 0
2347           *gensym-counter* 0
2348           *literal-counter* 0
2349           *block-counter* 0)
2350     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))