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