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