4ed550d0535010c7a52c1c67a7cea42b4170149b
[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                        '(lambda (name args &rest body)
30                          `(eval-when-compile
31                             (%compile-defmacro ',name
32                                                '(lambda ,(mapcar (lambda (x)
33                                                                    (if (eq x '&body)
34                                                                        '&rest
35                                                                        x))
36                                                                  args)
37                                                  ,@body))))))
38
39   (defmacro declaim (&rest decls)
40     `(eval-when-compile
41        ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
42
43   (declaim (constant nil t))
44   (setq nil 'nil)
45   (setq t 't)
46
47   (defmacro when (condition &body body)
48     `(if ,condition (progn ,@body) nil))
49
50   (defmacro unless (condition &body body)
51     `(if ,condition nil (progn ,@body)))
52
53   (defmacro defvar (name value &optional docstring)
54     `(progn
55        (unless (boundp ',name) (setq ,name ,value))
56        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
57        ',name))
58
59   (defmacro defparameter (name value &optional docstring)
60     `(progn
61        (setq ,name ,value)
62        ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
63        ',name))
64
65   (defmacro named-lambda (name args &rest body)
66     (let ((x (gensym "FN")))
67       `(let ((,x (lambda ,args ,@body)))
68          (oset ,x "fname" ,name)
69          ,x)))
70
71   (defmacro defun (name args &rest body)
72     `(progn
73        (declaim (non-overridable ,name))
74        (fset ',name
75              (named-lambda ,(symbol-name name) ,args
76                ,@(if (and (stringp (car body)) (not (null (cdr body))))
77                      `(,(car body) (block ,name ,@(cdr body)))
78                      `((block ,name ,@body)))))
79        ',name))
80
81   (defun null (x)
82     (eq x nil))
83
84   (defmacro return (&optional value)
85     `(return-from nil ,value))
86
87   (defmacro while (condition &body body)
88     `(block nil (%while ,condition ,@body)))
89
90   (defvar *gensym-counter* 0)
91   (defun gensym (&optional (prefix "G"))
92     (setq *gensym-counter* (+ *gensym-counter* 1))
93     (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
94
95   (defun boundp (x)
96     (boundp x))
97
98   ;; Basic functions
99   (defun = (x y) (= x y))
100   (defun + (x y) (+ x y))
101   (defun - (x y) (- x y))
102   (defun * (x y) (* x y))
103   (defun / (x y) (/ x y))
104   (defun 1+ (x) (+ x 1))
105   (defun 1- (x) (- x 1))
106   (defun zerop (x) (= x 0))
107   (defun truncate (x y) (floor (/ x y)))
108
109   (defun eql (x y) (eq x y))
110
111   (defun not (x) (if x nil t))
112
113   (defun cons (x y ) (cons x y))
114   (defun consp (x) (consp x))
115
116   (defun car (x)
117     "Return the CAR part of a cons, or NIL if X is null."
118     (car x))
119
120   (defun cdr (x) (cdr x))
121   (defun caar (x) (car (car x)))
122   (defun cadr (x) (car (cdr x)))
123   (defun cdar (x) (cdr (car x)))
124   (defun cddr (x) (cdr (cdr x)))
125   (defun caddr (x) (car (cdr (cdr x))))
126   (defun cdddr (x) (cdr (cdr (cdr x))))
127   (defun cadddr (x) (car (cdr (cdr (cdr x)))))
128   (defun first (x) (car x))
129   (defun second (x) (cadr x))
130   (defun third (x) (caddr x))
131   (defun fourth (x) (cadddr x))
132
133   (defun list (&rest args) args)
134   (defun atom (x)
135     (not (consp x)))
136
137   ;; Basic macros
138
139   (defmacro incf (x &optional (delta 1))
140     `(setq ,x (+ ,x ,delta)))
141
142   (defmacro decf (x &optional (delta 1))
143     `(setq ,x (- ,x ,delta)))
144
145   (defmacro push (x place)
146     `(setq ,place (cons ,x ,place)))
147
148   (defmacro dolist (iter &body body)
149     (let ((var (first iter))
150           (g!list (gensym)))
151       `(block nil
152          (let ((,g!list ,(second iter))
153                (,var nil))
154            (%while ,g!list
155                    (setq ,var (car ,g!list))
156                    (tagbody ,@body)
157                    (setq ,g!list (cdr ,g!list)))
158            ,(third iter)))))
159
160   (defmacro dotimes (iter &body body)
161     (let ((g!to (gensym))
162           (var (first iter))
163           (to (second iter))
164           (result (third iter)))
165       `(block nil
166          (let ((,var 0)
167                (,g!to ,to))
168            (%while (< ,var ,g!to)
169                    (tagbody ,@body)
170                    (incf ,var))
171            ,result))))
172
173   (defmacro cond (&rest clausules)
174     (if (null clausules)
175         nil
176         (if (eq (caar clausules) t)
177             `(progn ,@(cdar clausules))
178             `(if ,(caar clausules)
179                  (progn ,@(cdar clausules))
180                  (cond ,@(cdr clausules))))))
181
182   (defmacro case (form &rest clausules)
183     (let ((!form (gensym)))
184       `(let ((,!form ,form))
185          (cond
186            ,@(mapcar (lambda (clausule)
187                        (if (eq (car clausule) t)
188                            clausule
189                            `((eql ,!form ',(car clausule))
190                              ,@(cdr clausule))))
191                      clausules)))))
192
193   (defmacro ecase (form &rest clausules)
194     `(case ,form
195        ,@(append
196           clausules
197           `((t
198              (error "ECASE expression failed."))))))
199
200   (defmacro and (&rest forms)
201     (cond
202       ((null forms)
203        t)
204       ((null (cdr forms))
205        (car forms))
206       (t
207        `(if ,(car forms)
208             (and ,@(cdr forms))
209             nil))))
210
211   (defmacro or (&rest forms)
212     (cond
213       ((null forms)
214        nil)
215       ((null (cdr forms))
216        (car forms))
217       (t
218        (let ((g (gensym)))
219          `(let ((,g ,(car forms)))
220             (if ,g ,g (or ,@(cdr forms))))))))
221
222   (defmacro prog1 (form &body body)
223     (let ((value (gensym)))
224       `(let ((,value ,form))
225          ,@body
226          ,value)))
227
228   (defmacro prog2 (form1 result &body body)
229     `(prog1 (progn ,form1 ,result) ,@body)))
230
231
232 ;;; This couple of helper functions will be defined in both Common
233 ;;; Lisp and in Ecmalisp.
234 (defun ensure-list (x)
235   (if (listp x)
236       x
237       (list x)))
238
239 (defun !reduce (func list initial)
240   (if (null list)
241       initial
242       (!reduce func
243                (cdr list)
244                (funcall func initial (car list)))))
245
246 ;;; Go on growing the Lisp language in Ecmalisp, with more high
247 ;;; level utilities as well as correct versions of other
248 ;;; constructions.
249 #+ecmalisp
250 (progn
251   (defun append-two (list1 list2)
252     (if (null list1)
253         list2
254         (cons (car list1)
255               (append (cdr list1) list2))))
256
257   (defun append (&rest lists)
258     (!reduce #'append-two lists '()))
259
260   (defun revappend (list1 list2)
261     (while list1
262       (push (car list1) list2)
263       (setq list1 (cdr list1)))
264     list2)
265
266   (defun reverse (list)
267     (revappend list '()))
268
269   (defun list-length (list)
270     (let ((l 0))
271       (while (not (null list))
272         (incf l)
273         (setq list (cdr list)))
274       l))
275
276   (defun length (seq)
277     (if (stringp seq)
278         (string-length seq)
279         (list-length seq)))
280
281   (defun concat-two (s1 s2)
282     (concat-two s1 s2))
283
284   (defun mapcar (func list)
285     (if (null list)
286         '()
287         (cons (funcall func (car list))
288               (mapcar func (cdr list)))))
289
290   (defun identity (x) x)
291
292   (defun copy-list (x)
293     (mapcar #'identity x))
294
295   (defun code-char (x) x)
296   (defun char-code (x) x)
297   (defun char= (x y) (= x y))
298
299   (defun integerp (x)
300     (and (numberp x) (= (floor x) x)))
301
302   (defun plusp (x) (< 0 x))
303   (defun minusp (x) (< x 0))
304
305   (defun listp (x)
306     (or (consp x) (null x)))
307
308   (defun nthcdr (n list)
309     (while (and (plusp n) list)
310       (setq n (1- n))
311       (setq list (cdr list)))
312     list)
313
314   (defun nth (n list)
315     (car (nthcdr n list)))
316
317   (defun last (x)
318     (while (consp (cdr x))
319       (setq x (cdr x)))
320     x)
321
322   (defun butlast (x)
323     (and (consp (cdr x))
324          (cons (car x) (butlast (cdr x)))))
325
326   (defun member (x list)
327     (while list
328       (when (eql x (car list))
329         (return list))
330       (setq list (cdr list))))
331
332   (defun remove (x list)
333     (cond
334       ((null list)
335        nil)
336       ((eql x (car list))
337        (remove x (cdr list)))
338       (t
339        (cons (car list) (remove x (cdr list))))))
340
341   (defun remove-if (func list)
342     (cond
343       ((null list)
344        nil)
345       ((funcall func (car list))
346        (remove-if func (cdr list)))
347       (t
348        (cons (car list) (remove-if func (cdr list))))))
349
350   (defun remove-if-not (func list)
351     (cond
352       ((null list)
353        nil)
354       ((funcall func (car list))
355        (cons (car list) (remove-if-not func (cdr list))))
356       (t
357        (remove-if-not func (cdr list)))))
358
359   (defun digit-char-p (x)
360     (if (and (<= #\0 x) (<= x #\9))
361         (- x #\0)
362         nil))
363
364   (defun subseq (seq a &optional b)
365     (cond
366       ((stringp seq)
367        (if b
368            (slice seq a b)
369            (slice seq a)))
370       (t
371        (error "Unsupported argument."))))
372
373   (defun parse-integer (string)
374     (let ((value 0)
375           (index 0)
376           (size (length string)))
377       (while (< index size)
378         (setq value (+ (* value 10) (digit-char-p (char string index))))
379         (incf index))
380       value))
381
382   (defun some (function seq)
383     (cond
384       ((stringp seq)
385        (let ((index 0)
386              (size (length seq)))
387          (while (< index size)
388            (when (funcall function (char seq index))
389              (return-from some t))
390            (incf index))
391          nil))
392       ((listp seq)
393        (dolist (x seq nil)
394          (when (funcall function x)
395            (return t))))
396       (t
397        (error "Unknown sequence."))))
398
399   (defun every (function seq)
400     (cond
401       ((stringp seq)
402        (let ((index 0)
403              (size (length seq)))
404          (while (< index size)
405            (unless (funcall function (char seq index))
406              (return-from every nil))
407            (incf index))
408          t))
409       ((listp seq)
410        (dolist (x seq t)
411          (unless (funcall function x)
412            (return))))
413       (t
414        (error "Unknown sequence."))))
415
416   (defun assoc (x alist)
417     (while alist
418       (if (eql x (caar alist))
419           (return)
420           (setq alist (cdr alist))))
421     (car alist))
422
423   (defun string (x)
424     (cond ((stringp x) x)
425           ((symbolp x) (symbol-name x))
426           (t (char-to-string x))))
427
428   (defun string= (s1 s2)
429     (equal s1 s2))
430
431   (defun fdefinition (x)
432     (cond
433       ((functionp x)
434        x)
435       ((symbolp x)
436        (symbol-function x))
437       (t
438        (error "Invalid function"))))
439
440   (defun disassemble (function)
441     (write-line (lambda-code (fdefinition function)))
442     nil)
443
444   (defun documentation (x type)
445     "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
446     (ecase type
447       (function
448        (let ((func (fdefinition x)))
449          (oget func "docstring")))
450       (variable
451        (unless (symbolp x)
452          (error "Wrong argument type! it should be a symbol"))
453        (oget x "vardoc"))))
454
455   ;; Packages
456
457   (defvar *package-list* nil)
458
459   (defun make-package (name)
460     (let ((package (new)))
461       (oset package "packageName" name)
462       (oset package "symbols" (new))
463       (push package *package-list*)
464       package))
465
466   (defun packagep (x)
467     (and (objectp x) (in "symbols" x)))
468
469   (defun find-package (package-designator)
470     (when (packagep package-designator)
471       (return-from find-package package-designator))
472     (let ((name (string package-designator)))
473       (dolist (package *package-list*)
474         (when (string= (package-name package) name)
475           (return package)))))
476
477   (defun find-package-or-fail (package-designator)
478     (or (find-package package-designator)
479         (error "Package unknown.")))
480
481   (defun package-name (package-designator)
482     (let ((package (find-package-or-fail package-designator)))
483       (oget package "packageName")))
484
485   (defun %package-symbols (package-designator)
486     (let ((package (find-package-or-fail package-designator)))
487       (oget package "symbols")))
488
489   (defvar *package*
490     (make-package "CL"))
491
492   ;; This function is used internally to initialize the CL package
493   ;; with the symbols built during bootstrap.
494   (defun %intern-symbol (symbol)
495     (let ((symbols (%package-symbols *package*)))
496       (oset symbol "package" *package*)
497       (oset symbols (symbol-name symbol) symbol)))
498
499   (defun intern (name &optional (package *package*))
500     (let ((symbols (%package-symbols package)))
501       (if (in name symbols)
502           (oget symbols name)
503           (let ((symbol (make-symbol name)))
504             (oset symbol "package" package)
505             (oset symbols name symbol)))))
506
507   (defun find-symbol (name &optional (package *package*))
508     (let ((symbols (%package-symbols package)))
509       (oget *package* name)))
510
511   (defun symbol-package (symbol)
512     (unless (symbolp symbol)
513       (error "it is not a symbol"))
514     (oget symbol "package")))
515
516
517
518 ;;; The compiler offers some primitives and special forms which are
519 ;;; not found in Common Lisp, for instance, while. So, we grow Common
520 ;;; Lisp a bit to it can execute the rest of the file.
521 #+common-lisp
522 (progn
523   (defmacro while (condition &body body)
524     `(do ()
525          ((not ,condition))
526        ,@body))
527
528   (defmacro eval-when-compile (&body body)
529     `(eval-when (:compile-toplevel :load-toplevel :execute)
530        ,@body))
531
532   (defun concat-two (s1 s2)
533     (concatenate 'string s1 s2))
534
535   (defun setcar (cons new)
536     (setf (car cons) new))
537   (defun setcdr (cons new)
538     (setf (cdr cons) new)))
539
540 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
541 ;;; from here, this code will compile on both. We define some helper
542 ;;; functions now for string manipulation and so on. They will be
543 ;;; useful in the compiler, mostly.
544
545 (defvar *newline* (string (code-char 10)))
546
547 (defun concat (&rest strs)
548   (!reduce #'concat-two strs ""))
549
550 (defmacro concatf (variable &body form)
551   `(setq ,variable (concat ,variable (progn ,@form))))
552
553 ;;; Concatenate a list of strings, with a separator
554 (defun join (list &optional (separator ""))
555   (cond
556     ((null list)
557      "")
558     ((null (cdr list))
559      (car list))
560     (t
561      (concat (car list)
562              separator
563              (join (cdr list) separator)))))
564
565 (defun join-trailing (list &optional (separator ""))
566   (if (null list)
567       ""
568       (concat (car list) separator (join-trailing (cdr list) separator))))
569
570 (defun mapconcat (func list)
571   (join (mapcar func list)))
572
573 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
574 ;;; of this function are available, because the Ecmalisp version is
575 ;;; very slow and bootstraping was annoying.
576
577 #+ecmalisp
578 (defun indent (&rest string)
579   (let ((input (join string)))
580     (let ((output "")
581           (index 0)
582           (size (length input)))
583       (when (plusp (length input)) (concatf output "    "))
584       (while (< index size)
585         (let ((str
586                (if (and (char= (char input index) #\newline)
587                         (< index (1- size))
588                         (not (char= (char input (1+ index)) #\newline)))
589                    (concat (string #\newline) "    ")
590                    (string (char input index)))))
591           (concatf output str))
592         (incf index))
593       output)))
594
595 #+common-lisp
596 (defun indent (&rest string)
597   (with-output-to-string (*standard-output*)
598     (with-input-from-string (input (join string))
599       (loop
600          for line = (read-line input nil)
601          while line
602          do (write-string "    ")
603          do (write-line line)))))
604
605
606 (defun integer-to-string (x)
607   (cond
608     ((zerop x)
609      "0")
610     ((minusp x)
611      (concat "-" (integer-to-string (- 0 x))))
612     (t
613      (let ((digits nil))
614        (while (not (zerop x))
615          (push (mod x 10) digits)
616          (setq x (truncate x 10)))
617        (join (mapcar (lambda (d) (string (char "0123456789" d)))
618                      digits))))))
619
620
621 ;;; Wrap X with a Javascript code to convert the result from
622 ;;; Javascript generalized booleans to T or NIL.
623 (defun js!bool (x)
624   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
625
626 ;;; Concatenate the arguments and wrap them with a self-calling
627 ;;; Javascript anonymous function. It is used to make some Javascript
628 ;;; statements valid expressions and provide a private scope as well.
629 ;;; It could be defined as function, but we could do some
630 ;;; preprocessing in the future.
631 (defmacro js!selfcall (&body body)
632   `(concat "(function(){" *newline* (indent ,@body) "})()"))
633
634
635 ;;; Printer
636
637 #+ecmalisp
638 (progn
639   (defun prin1-to-string (form)
640     (cond
641       ((symbolp form) (symbol-name form))
642       ((integerp form) (integer-to-string form))
643       ((stringp form) (concat "\"" (escape-string form) "\""))
644       ((functionp form)
645        (let ((name (oget form "fname")))
646          (if name
647              (concat "#<FUNCTION " name ">")
648              (concat "#<FUNCTION>"))))
649       ((listp form)
650        (concat "("
651                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
652                (let ((last (last form)))
653                  (if (null (cdr last))
654                      (prin1-to-string (car last))
655                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
656                ")"))
657       ((packagep form)
658        (concat "#<PACKAGE " (package-name form) ">"))))
659
660   (defun write-line (x)
661     (write-string x)
662     (write-string *newline*)
663     x)
664
665   (defun warn (string)
666     (write-string "WARNING: ")
667     (write-line string))
668
669   (defun print (x)
670     (write-line (prin1-to-string x))
671     x))
672
673
674 ;;;; Reader
675
676 ;;; The Lisp reader, parse strings and return Lisp objects. The main
677 ;;; entry points are `ls-read' and `ls-read-from-string'.
678
679 (defun make-string-stream (string)
680   (cons string 0))
681
682 (defun %peek-char (stream)
683   (and (< (cdr stream) (length (car stream)))
684        (char (car stream) (cdr stream))))
685
686 (defun %read-char (stream)
687   (and (< (cdr stream) (length (car stream)))
688        (prog1 (char (car stream) (cdr stream))
689          (setcdr stream (1+ (cdr stream))))))
690
691 (defun whitespacep (ch)
692   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
693
694 (defun skip-whitespaces (stream)
695   (let (ch)
696     (setq ch (%peek-char stream))
697     (while (and ch (whitespacep ch))
698       (%read-char stream)
699       (setq ch (%peek-char stream)))))
700
701 (defun terminalp (ch)
702   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
703
704 (defun read-until (stream func)
705   (let ((string "")
706         (ch))
707     (setq ch (%peek-char stream))
708     (while (and ch (not (funcall func ch)))
709       (setq string (concat string (string ch)))
710       (%read-char stream)
711       (setq ch (%peek-char stream)))
712     string))
713
714 (defun skip-whitespaces-and-comments (stream)
715   (let (ch)
716     (skip-whitespaces stream)
717     (setq ch (%peek-char stream))
718     (while (and ch (char= ch #\;))
719       (read-until stream (lambda (x) (char= x #\newline)))
720       (skip-whitespaces stream)
721       (setq ch (%peek-char stream)))))
722
723 (defun %read-list (stream)
724   (skip-whitespaces-and-comments stream)
725   (let ((ch (%peek-char stream)))
726     (cond
727       ((null ch)
728        (error "Unspected EOF"))
729       ((char= ch #\))
730        (%read-char stream)
731        nil)
732       ((char= ch #\.)
733        (%read-char stream)
734        (prog1 (ls-read stream)
735          (skip-whitespaces-and-comments stream)
736          (unless (char= (%read-char stream) #\))
737            (error "')' was expected."))))
738       (t
739        (cons (ls-read stream) (%read-list stream))))))
740
741 (defun read-string (stream)
742   (let ((string "")
743         (ch nil))
744     (setq ch (%read-char stream))
745     (while (not (eql ch #\"))
746       (when (null ch)
747         (error "Unexpected EOF"))
748       (when (eql ch #\\)
749         (setq ch (%read-char stream)))
750       (setq string (concat string (string ch)))
751       (setq ch (%read-char stream)))
752     string))
753
754 (defun read-sharp (stream)
755   (%read-char stream)
756   (ecase (%read-char stream)
757     (#\'
758      (list 'function (ls-read stream)))
759     (#\\
760      (let ((cname
761             (concat (string (%read-char stream))
762                     (read-until stream #'terminalp))))
763        (cond
764          ((string= cname "space") (char-code #\space))
765          ((string= cname "tab") (char-code #\tab))
766          ((string= cname "newline") (char-code #\newline))
767          (t (char-code (char cname 0))))))
768     (#\+
769      (let ((feature (read-until stream #'terminalp)))
770        (cond
771          ((string= feature "common-lisp")
772           (ls-read stream)              ;ignore
773           (ls-read stream))
774          ((string= feature "ecmalisp")
775           (ls-read stream))
776          (t
777           (error "Unknown reader form.")))))))
778
779 (defvar *eof* (make-symbol "EOF"))
780 (defun ls-read (stream)
781   (skip-whitespaces-and-comments stream)
782   (let ((ch (%peek-char stream)))
783     (cond
784       ((null ch)
785        *eof*)
786       ((char= ch #\()
787        (%read-char stream)
788        (%read-list stream))
789       ((char= ch #\')
790        (%read-char stream)
791        (list 'quote (ls-read stream)))
792       ((char= ch #\`)
793        (%read-char stream)
794        (list 'backquote (ls-read stream)))
795       ((char= ch #\")
796        (%read-char stream)
797        (read-string stream))
798       ((char= ch #\,)
799        (%read-char stream)
800        (if (eql (%peek-char stream) #\@)
801            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
802            (list 'unquote (ls-read stream))))
803       ((char= ch #\#)
804        (read-sharp stream))
805       (t
806        (let ((string (read-until stream #'terminalp)))
807          (if (every #'digit-char-p string)
808              (parse-integer string)
809              (intern (string-upcase string))))))))
810
811 (defun ls-read-from-string (string)
812   (ls-read (make-string-stream string)))
813
814
815 ;;;; Compiler
816
817 ;;; Translate the Lisp code to Javascript. It will compile the special
818 ;;; forms. Some primitive functions are compiled as special forms
819 ;;; too. The respective real functions are defined in the target (see
820 ;;; the beginning of this file) as well as some primitive functions.
821
822 (defvar *compilation-unit-checks* '())
823
824 (defun make-binding (name type value &optional declarations)
825   (list name type value declarations))
826
827 (defun binding-name (b) (first b))
828 (defun binding-type (b) (second b))
829 (defun binding-value (b) (third b))
830 (defun binding-declarations (b) (fourth b))
831
832 (defun set-binding-value (b value)
833   (setcar (cddr b) value))
834
835 (defun set-binding-declarations (b value)
836   (setcar (cdddr b) value))
837
838 (defun push-binding-declaration (decl b)
839   (set-binding-declarations b (cons decl (binding-declarations b))))
840
841
842 (defun make-lexenv ()
843   (list nil nil nil nil))
844
845 (defun copy-lexenv (lexenv)
846   (copy-list lexenv))
847
848 (defun push-to-lexenv (binding lexenv namespace)
849   (ecase namespace
850     (variable   (setcar        lexenv  (cons binding (car lexenv))))
851     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
852     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
853     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
854
855 (defun extend-lexenv (bindings lexenv namespace)
856   (let ((env (copy-lexenv lexenv)))
857     (dolist (binding (reverse bindings) env)
858       (push-to-lexenv binding env namespace))))
859
860 (defun lookup-in-lexenv (name lexenv namespace)
861   (assoc name (ecase namespace
862                 (variable (first lexenv))
863                 (function (second lexenv))
864                 (block (third lexenv))
865                 (gotag (fourth lexenv)))))
866
867 (defvar *environment* (make-lexenv))
868
869 (defvar *variable-counter* 0)
870 (defun gvarname (symbol)
871   (concat "v" (integer-to-string (incf *variable-counter*))))
872
873 (defun translate-variable (symbol)
874   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
875
876 (defun extend-local-env (args)
877   (let ((new (copy-lexenv *environment*)))
878     (dolist (symbol args new)
879       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
880         (push-to-lexenv b new 'variable)))))
881
882 ;;; Toplevel compilations
883 (defvar *toplevel-compilations* nil)
884
885 (defun toplevel-compilation (string)
886   (push string *toplevel-compilations*))
887
888 (defun null-or-empty-p (x)
889   (zerop (length x)))
890
891 (defun get-toplevel-compilations ()
892   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
893
894 (defun %compile-defmacro (name lambda)
895   (toplevel-compilation (ls-compile `',name))
896   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
897
898 (defun global-binding (name type namespace)
899   (or (lookup-in-lexenv name *environment* namespace)
900       (let ((b (make-binding name type nil)))
901         (push-to-lexenv b *environment* namespace)
902         b)))
903
904 (defun claimp (symbol namespace claim)
905   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
906     (and b (member claim (binding-declarations b)))))
907
908 (defun !proclaim (decl)
909   (case (car decl)
910     (notinline
911      (dolist (name (cdr decl))
912        (let ((b (global-binding name 'function 'function)))
913          (push-binding-declaration 'notinline b))))
914     (constant
915      (dolist (name (cdr decl))
916        (let ((b (global-binding name 'variable 'variable)))
917          (push-binding-declaration 'constant b))))
918     (non-overridable
919      (dolist (name (cdr decl))
920        (let ((b (global-binding name 'function 'function)))
921          (push-binding-declaration 'non-overridable b))))))
922
923 #+ecmalisp
924 (fset 'proclaim #'!proclaim)
925
926 ;;; Special forms
927
928 (defvar *compilations* nil)
929
930 (defmacro define-compilation (name args &body body)
931   ;; Creates a new primitive `name' with parameters args and
932   ;; @body. The body can access to the local environment through the
933   ;; variable *ENVIRONMENT*.
934   `(push (list ',name (lambda ,args (block ,name ,@body)))
935          *compilations*))
936
937 (define-compilation if (condition true false)
938   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
939           " ? " (ls-compile true)
940           " : " (ls-compile false)
941           ")"))
942
943 (defvar *lambda-list-keywords* '(&optional &rest))
944
945 (defun list-until-keyword (list)
946   (if (or (null list) (member (car list) *lambda-list-keywords*))
947       nil
948       (cons (car list) (list-until-keyword (cdr list)))))
949
950 (defun lambda-list-required-arguments (lambda-list)
951   (list-until-keyword lambda-list))
952
953 (defun lambda-list-optional-arguments-with-default (lambda-list)
954   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
955
956 (defun lambda-list-optional-arguments (lambda-list)
957   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
958
959 (defun lambda-list-rest-argument (lambda-list)
960   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
961     (when (cdr rest)
962       (error "Bad lambda-list"))
963     (car rest)))
964
965
966 (defun lambda-docstring-wrapper (docstring &rest strs)
967   (if docstring
968       (js!selfcall
969         "var func = " (join strs) ";" *newline*
970         "func.docstring = '" docstring "';" *newline*
971         "return func;" *newline*)
972       (join strs)))
973
974 (define-compilation lambda (lambda-list &rest body)
975   (let ((required-arguments (lambda-list-required-arguments lambda-list))
976         (optional-arguments (lambda-list-optional-arguments lambda-list))
977         (rest-argument (lambda-list-rest-argument lambda-list))
978         documentation)
979     ;; Get the documentation string for the lambda function
980     (when (and (stringp (car body))
981                (not (null (cdr body))))
982       (setq documentation (car body))
983       (setq body (cdr body)))
984     (let ((n-required-arguments (length required-arguments))
985           (n-optional-arguments (length optional-arguments))
986           (*environment* (extend-local-env
987                           (append (ensure-list rest-argument)
988                                   required-arguments
989                                   optional-arguments))))
990       (lambda-docstring-wrapper
991        documentation
992        "(function ("
993        (join (mapcar #'translate-variable
994                      (append required-arguments optional-arguments))
995              ",")
996        "){" *newline*
997        ;; Check number of arguments
998        (indent
999         (if required-arguments
1000             (concat "if (arguments.length < " (integer-to-string n-required-arguments)
1001                     ") throw 'too few arguments';" *newline*)
1002             "")
1003         (if (not rest-argument)
1004             (concat "if (arguments.length > "
1005                     (integer-to-string (+ n-required-arguments n-optional-arguments))
1006                     ") throw 'too many arguments';" *newline*)
1007             "")
1008         ;; Optional arguments
1009         (if optional-arguments
1010             (concat "switch(arguments.length){" *newline*
1011                     (let ((optional-and-defaults
1012                            (lambda-list-optional-arguments-with-default lambda-list))
1013                           (cases nil)
1014                           (idx 0))
1015                       (progn
1016                         (while (< idx n-optional-arguments)
1017                           (let ((arg (nth idx optional-and-defaults)))
1018                             (push (concat "case "
1019                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1020                                           (translate-variable (car arg))
1021                                           "="
1022                                           (ls-compile (cadr arg))
1023                                           ";" *newline*)
1024                                   cases)
1025                             (incf idx)))
1026                         (push (concat "default: break;" *newline*) cases)
1027                         (join (reverse cases))))
1028                     "}" *newline*)
1029             "")
1030         ;; &rest/&body argument
1031         (if rest-argument
1032             (let ((js!rest (translate-variable rest-argument)))
1033               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1034                       "for (var i = arguments.length-1; i>="
1035                       (integer-to-string (+ n-required-arguments n-optional-arguments))
1036                       "; i--)" *newline*
1037                       (indent js!rest " = "
1038                               "{car: arguments[i], cdr: ") js!rest "};"
1039                       *newline*))
1040             "")
1041         ;; Body
1042         (ls-compile-block body t)) *newline*
1043        "})"))))
1044
1045 (define-compilation setq (var val)
1046   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1047     (if (eq (binding-type b) 'lexical-variable)
1048         (concat (binding-value b) " = " (ls-compile val))
1049         (ls-compile `(set ',var ,val)))))
1050
1051 ;;; FFI Variable accessors
1052 (define-compilation js-vref (var)
1053   var)
1054
1055 (define-compilation js-vset (var val)
1056   (concat "(" var " = " (ls-compile val) ")"))
1057
1058
1059 ;;; Literals
1060 (defun escape-string (string)
1061   (let ((output "")
1062         (index 0)
1063         (size (length string)))
1064     (while (< index size)
1065       (let ((ch (char string index)))
1066         (when (or (char= ch #\") (char= ch #\\))
1067           (setq output (concat output "\\")))
1068         (when (or (char= ch #\newline))
1069           (setq output (concat output "\\"))
1070           (setq ch #\n))
1071         (setq output (concat output (string ch))))
1072       (incf index))
1073     output))
1074
1075
1076 (defvar *literal-symbols* nil)
1077 (defvar *literal-counter* 0)
1078
1079 (defun genlit ()
1080   (concat "l" (integer-to-string (incf *literal-counter*))))
1081
1082 (defun literal (sexp &optional recursive)
1083   (cond
1084     ((integerp sexp) (integer-to-string sexp))
1085     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1086     ((symbolp sexp)
1087      (or (cdr (assoc sexp *literal-symbols*))
1088          (let ((v (genlit))
1089                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1090                   #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
1091            (push (cons sexp v) *literal-symbols*)
1092            (toplevel-compilation (concat "var " v " = " s))
1093            v)))
1094     ((consp sexp)
1095      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1096                       "cdr: " (literal (cdr sexp) t) "}")))
1097        (if recursive
1098            c
1099            (let ((v (genlit)))
1100              (toplevel-compilation (concat "var " v " = " c))
1101              v))))))
1102
1103 (define-compilation quote (sexp)
1104   (literal sexp))
1105
1106 (define-compilation %while (pred &rest body)
1107   (js!selfcall
1108     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1109     (indent (ls-compile-block body))
1110     "}"
1111     "return " (ls-compile nil) ";" *newline*))
1112
1113 (define-compilation function (x)
1114   (cond
1115     ((and (listp x) (eq (car x) 'lambda))
1116      (ls-compile x))
1117     ((symbolp x)
1118      (ls-compile `(symbol-function ',x)))))
1119
1120 (define-compilation eval-when-compile (&rest body)
1121   (eval (cons 'progn body))
1122   nil)
1123
1124 (defmacro define-transformation (name args form)
1125   `(define-compilation ,name ,args
1126      (ls-compile ,form)))
1127
1128 (define-compilation progn (&rest body)
1129   (js!selfcall (ls-compile-block body t)))
1130
1131 (defun dynamic-binding-wrapper (bindings body)
1132   (if (null bindings)
1133       body
1134       (concat
1135        "try {" *newline*
1136        (indent
1137         "var tmp;" *newline*
1138         (join
1139          (mapcar (lambda (b)
1140                    (let ((s (ls-compile `(quote ,(car b)))))
1141                      (concat "tmp = " s ".value;" *newline*
1142                              s ".value = " (cdr b) ";" *newline*
1143                              (cdr b) " = tmp;" *newline*)))
1144                  bindings))
1145         body)
1146        "}" *newline*
1147        "finally {"  *newline*
1148        (indent
1149         (join-trailing
1150          (mapcar (lambda (b)
1151                    (let ((s (ls-compile `(quote ,(car b)))))
1152                      (concat s ".value" " = " (cdr b))))
1153                  bindings)
1154          (concat ";" *newline*)))
1155        "}" *newline*)))
1156
1157
1158 (define-compilation let (bindings &rest body)
1159   (let ((bindings (mapcar #'ensure-list bindings)))
1160     (let ((variables (mapcar #'first bindings))
1161           (values    (mapcar #'second bindings)))
1162       (let ((cvalues (mapcar #'ls-compile values))
1163             (*environment* (extend-local-env (remove-if #'boundp variables)))
1164             (dynamic-bindings))
1165         (concat "(function("
1166                 (join (mapcar (lambda (x)
1167                                 (if (boundp x)
1168                                     (let ((v (gvarname x)))
1169                                       (push (cons x v) dynamic-bindings)
1170                                       v)
1171                                     (translate-variable x)))
1172                               variables)
1173                       ",")
1174                 "){" *newline*
1175                 (let ((body (ls-compile-block body t)))
1176                   (indent (dynamic-binding-wrapper dynamic-bindings body)))
1177                 "})(" (join cvalues ",") ")")))))
1178
1179
1180 (defvar *block-counter* 0)
1181
1182 (define-compilation block (name &rest body)
1183   (let ((tr (integer-to-string (incf *block-counter*))))
1184     (let ((b (make-binding name 'block tr)))
1185       (js!selfcall
1186         "try {" *newline*
1187         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1188           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1189         "}" *newline*
1190         "catch (cf){" *newline*
1191         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1192         "        return cf.value;" *newline*
1193         "    else" *newline*
1194         "        throw cf;" *newline*
1195         "}" *newline*))))
1196
1197 (define-compilation return-from (name &optional value)
1198   (let ((b (lookup-in-lexenv name *environment* 'block)))
1199     (if b
1200         (js!selfcall
1201           "throw ({"
1202           "type: 'block', "
1203           "id: " (binding-value b) ", "
1204           "value: " (ls-compile value) ", "
1205           "message: 'Return from unknown block " (symbol-name name) ".'"
1206           "})")
1207         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1208
1209
1210 (define-compilation catch (id &rest body)
1211   (js!selfcall
1212     "var id = " (ls-compile id) ";" *newline*
1213     "try {" *newline*
1214     (indent "return " (ls-compile `(progn ,@body))
1215             ";" *newline*)
1216     "}" *newline*
1217     "catch (cf){" *newline*
1218     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1219     "        return cf.value;" *newline*
1220     "    else" *newline*
1221     "        throw cf;" *newline*
1222     "}" *newline*))
1223
1224 (define-compilation throw (id &optional value)
1225   (js!selfcall
1226     "throw ({"
1227     "type: 'catch', "
1228     "id: " (ls-compile id) ", "
1229     "value: " (ls-compile value) ", "
1230     "message: 'Throw uncatched.'"
1231     "})"))
1232
1233
1234 (defvar *tagbody-counter* 0)
1235 (defvar *go-tag-counter* 0)
1236
1237 (defun go-tag-p (x)
1238   (or (integerp x) (symbolp x)))
1239
1240 (defun declare-tagbody-tags (tbidx body)
1241   (let ((bindings
1242          (mapcar (lambda (label)
1243                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1244                      (make-binding label 'gotag (list tbidx tagidx))))
1245                  (remove-if-not #'go-tag-p body))))
1246     (extend-lexenv bindings *environment* 'gotag)))
1247
1248 (define-compilation tagbody (&rest body)
1249   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1250   ;; because 1) it is easy and 2) many built-in forms expand to a
1251   ;; implicit tagbody, so we save some space.
1252   (unless (some #'go-tag-p body)
1253     (return-from tagbody (ls-compile `(progn ,@body nil))))
1254   ;; The translation assumes the first form in BODY is a label
1255   (unless (go-tag-p (car body))
1256     (push (gensym "START") body))
1257   ;; Tagbody compilation
1258   (let ((tbidx (integer-to-string *tagbody-counter*)))
1259     (let ((*environment* (declare-tagbody-tags tbidx body))
1260           initag)
1261       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1262         (setq initag (second (binding-value b))))
1263       (js!selfcall
1264         "var tagbody_" tbidx " = " initag ";" *newline*
1265         "tbloop:" *newline*
1266         "while (true) {" *newline*
1267         (indent "try {" *newline*
1268                 (indent (let ((content ""))
1269                           (concat "switch(tagbody_" tbidx "){" *newline*
1270                                   "case " initag ":" *newline*
1271                                   (dolist (form (cdr body) content)
1272                                     (concatf content
1273                                       (if (not (go-tag-p form))
1274                                           (indent (ls-compile form) ";" *newline*)
1275                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1276                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1277                                   "default:" *newline*
1278                                   "    break tbloop;" *newline*
1279                                   "}" *newline*)))
1280                 "}" *newline*
1281                 "catch (jump) {" *newline*
1282                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1283                 "        tagbody_" tbidx " = jump.label;" *newline*
1284                 "    else" *newline*
1285                 "        throw(jump);" *newline*
1286                 "}" *newline*)
1287         "}" *newline*
1288         "return " (ls-compile nil) ";" *newline*))))
1289
1290 (define-compilation go (label)
1291   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1292         (n (cond
1293              ((symbolp label) (symbol-name label))
1294              ((integerp label) (integer-to-string label)))))
1295     (if b
1296         (js!selfcall
1297           "throw ({"
1298           "type: 'tagbody', "
1299           "id: " (first (binding-value b)) ", "
1300           "label: " (second (binding-value b)) ", "
1301           "message: 'Attempt to GO to non-existing tag " n "'"
1302           "})" *newline*)
1303         (error (concat "Unknown tag `" n "'.")))))
1304
1305
1306 (define-compilation unwind-protect (form &rest clean-up)
1307   (js!selfcall
1308     "var ret = " (ls-compile nil) ";" *newline*
1309     "try {" *newline*
1310     (indent "ret = " (ls-compile form) ";" *newline*)
1311     "} finally {" *newline*
1312     (indent (ls-compile-block clean-up))
1313     "}" *newline*
1314     "return ret;" *newline*))
1315
1316
1317 ;;; A little backquote implementation without optimizations of any
1318 ;;; kind for ecmalisp.
1319 (defun backquote-expand-1 (form)
1320   (cond
1321     ((symbolp form)
1322      (list 'quote form))
1323     ((atom form)
1324      form)
1325     ((eq (car form) 'unquote)
1326      (car form))
1327     ((eq (car form) 'backquote)
1328      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1329     (t
1330      (cons 'append
1331            (mapcar (lambda (s)
1332                      (cond
1333                        ((and (listp s) (eq (car s) 'unquote))
1334                         (list 'list (cadr s)))
1335                        ((and (listp s) (eq (car s) 'unquote-splicing))
1336                         (cadr s))
1337                        (t
1338                         (list 'list (backquote-expand-1 s)))))
1339                    form)))))
1340
1341 (defun backquote-expand (form)
1342   (if (and (listp form) (eq (car form) 'backquote))
1343       (backquote-expand-1 (cadr form))
1344       form))
1345
1346 (defmacro backquote (form)
1347   (backquote-expand-1 form))
1348
1349 (define-transformation backquote (form)
1350   (backquote-expand-1 form))
1351
1352 ;;; Primitives
1353
1354 (defvar *builtins* nil)
1355
1356 (defmacro define-raw-builtin (name args &body body)
1357   ;; Creates a new primitive function `name' with parameters args and
1358   ;; @body. The body can access to the local environment through the
1359   ;; variable *ENVIRONMENT*.
1360   `(push (list ',name (lambda ,args (block ,name ,@body)))
1361          *builtins*))
1362
1363 (defmacro define-builtin (name args &body body)
1364   `(progn
1365      (define-raw-builtin ,name ,args
1366        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1367          ,@body))))
1368
1369 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1370 (defmacro type-check (decls &body body)
1371   `(js!selfcall
1372      ,@(mapcar (lambda (decl)
1373                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1374                  decls)
1375      ,@(mapcar (lambda (decl)
1376                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1377                           (indent "throw 'The value ' + "
1378                                   ,(first decl)
1379                                   " + ' is not a type "
1380                                   ,(second decl)
1381                                   ".';"
1382                                   *newline*)))
1383                decls)
1384      (concat "return " (progn ,@body) ";" *newline*)))
1385
1386 (defun num-op-num (x op y)
1387   (type-check (("x" "number" x) ("y" "number" y))
1388     (concat "x" op "y")))
1389
1390 (define-builtin + (x y) (num-op-num x "+" y))
1391 (define-builtin - (x y) (num-op-num x "-" y))
1392 (define-builtin * (x y) (num-op-num x "*" y))
1393 (define-builtin / (x y) (num-op-num x "/" y))
1394
1395 (define-builtin mod (x y) (num-op-num x "%" y))
1396
1397 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1398 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1399 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
1400 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1401 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1402
1403 (define-builtin numberp (x)
1404   (js!bool (concat "(typeof (" x ") == \"number\")")))
1405
1406 (define-builtin floor (x)
1407   (type-check (("x" "number" x))
1408     "Math.floor(x)"))
1409
1410 (define-builtin cons (x y)
1411   (concat "({car: " x ", cdr: " y "})"))
1412
1413 (define-builtin consp (x)
1414   (js!bool
1415    (js!selfcall
1416      "var tmp = " x ";" *newline*
1417      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1418
1419 (define-builtin car (x)
1420   (js!selfcall
1421     "var tmp = " x ";" *newline*
1422     "return tmp === " (ls-compile nil)
1423     "? " (ls-compile nil)
1424     ": tmp.car;" *newline*))
1425
1426 (define-builtin cdr (x)
1427   (js!selfcall
1428     "var tmp = " x ";" *newline*
1429     "return tmp === " (ls-compile nil) "? "
1430     (ls-compile nil)
1431     ": tmp.cdr;" *newline*))
1432
1433 (define-builtin setcar (x new)
1434   (type-check (("x" "object" x))
1435     (concat "(x.car = " new ")")))
1436
1437 (define-builtin setcdr (x new)
1438   (type-check (("x" "object" x))
1439     (concat "(x.cdr = " new ")")))
1440
1441 (define-builtin symbolp (x)
1442   (js!bool
1443    (js!selfcall
1444      "var tmp = " x ";" *newline*
1445      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1446
1447 (define-builtin make-symbol (name)
1448   (type-check (("name" "string" name))
1449     "({name: name})"))
1450
1451 (define-builtin symbol-name (x)
1452   (concat "(" x ").name"))
1453
1454 (define-builtin set (symbol value)
1455   (concat "(" symbol ").value = " value))
1456
1457 (define-builtin fset (symbol value)
1458   (concat "(" symbol ").function = " value))
1459
1460 (define-builtin boundp (x)
1461   (js!bool (concat "(" x ".value !== undefined)")))
1462
1463 (define-builtin symbol-value (x)
1464   (js!selfcall
1465     "var symbol = " x ";" *newline*
1466     "var value = symbol.value;" *newline*
1467     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1468     "return value;" *newline*))
1469
1470 (define-builtin symbol-function (x)
1471   (js!selfcall
1472     "var symbol = " x ";" *newline*
1473     "var func = symbol.function;" *newline*
1474     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1475     "return func;" *newline*))
1476
1477 (define-builtin symbol-plist (x)
1478   (concat "((" x ").plist || " (ls-compile nil) ")"))
1479
1480 (define-builtin lambda-code (x)
1481   (concat "(" x ").toString()"))
1482
1483
1484 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1485 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1486
1487 (define-builtin char-to-string (x)
1488   (type-check (("x" "number" x))
1489     "String.fromCharCode(x)"))
1490
1491 (define-builtin stringp (x)
1492   (js!bool (concat "(typeof(" x ") == \"string\")")))
1493
1494 (define-builtin string-upcase (x)
1495   (type-check (("x" "string" x))
1496     "x.toUpperCase()"))
1497
1498 (define-builtin string-length (x)
1499   (type-check (("x" "string" x))
1500     "x.length"))
1501
1502 (define-raw-builtin slice (string a &optional b)
1503   (js!selfcall
1504     "var str = " (ls-compile string) ";" *newline*
1505     "var a = " (ls-compile a) ";" *newline*
1506     "var b;" *newline*
1507     (if b
1508         (concat "b = " (ls-compile b) ";" *newline*)
1509         "")
1510     "return str.slice(a,b);" *newline*))
1511
1512 (define-builtin char (string index)
1513   (type-check (("string" "string" string)
1514                ("index" "number" index))
1515     "string.charCodeAt(index)"))
1516
1517 (define-builtin concat-two (string1 string2)
1518   (type-check (("string1" "string" string1)
1519                ("string2" "string" string2))
1520     "string1.concat(string2)"))
1521
1522 (define-raw-builtin funcall (func &rest args)
1523   (concat "(" (ls-compile func) ")("
1524           (join (mapcar #'ls-compile args)
1525                 ", ")
1526           ")"))
1527
1528 (define-raw-builtin apply (func &rest args)
1529   (if (null args)
1530       (concat "(" (ls-compile func) ")()")
1531       (let ((args (butlast args))
1532             (last (car (last args))))
1533         (js!selfcall
1534           "var f = " (ls-compile func) ";" *newline*
1535           "var args = [" (join (mapcar #'ls-compile args)
1536                                ", ")
1537           "];" *newline*
1538           "var tail = (" (ls-compile last) ");" *newline*
1539           "while (tail != " (ls-compile nil) "){" *newline*
1540           "    args.push(tail.car);" *newline*
1541           "    tail = tail.cdr;" *newline*
1542           "}" *newline*
1543           "return f.apply(this, args);" *newline*))))
1544
1545 (define-builtin js-eval (string)
1546   (type-check (("string" "string" string))
1547     "eval.apply(window, [string])"))
1548
1549 (define-builtin error (string)
1550   (js!selfcall "throw " string ";" *newline*))
1551
1552 (define-builtin new () "{}")
1553
1554 (define-builtin objectp (x)
1555   (js!bool (concat "(typeof (" x ") === 'object')")))
1556
1557 (define-builtin oget (object key)
1558   (js!selfcall
1559     "var tmp = " "(" object ")[" key "];" *newline*
1560     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1561
1562 (define-builtin oset (object key value)
1563   (concat "((" object ")[" key "] = " value ")"))
1564
1565 (define-builtin in (key object)
1566   (js!bool (concat "((" key ") in (" object "))")))
1567
1568 (define-builtin functionp (x)
1569   (js!bool (concat "(typeof " x " == 'function')")))
1570
1571 (define-builtin write-string (x)
1572   (type-check (("x" "string" x))
1573     "lisp.write(x)"))
1574
1575 (defun macro (x)
1576   (and (symbolp x)
1577        (let ((b (lookup-in-lexenv x *environment* 'function)))
1578          (and (eq (binding-type b) 'macro)
1579               b))))
1580
1581 (defun ls-macroexpand-1 (form)
1582   (let ((macro-binding (macro (car form))))
1583     (if macro-binding
1584         (let ((expander (binding-value macro-binding)))
1585           (when (listp expander)
1586             (let ((compiled (eval expander)))
1587               ;; The list representation are useful while
1588               ;; bootstrapping, as we can dump the definition of the
1589               ;; macros easily, but they are slow because we have to
1590               ;; evaluate them and compile them now and again. So, let
1591               ;; us replace the list representation version of the
1592               ;; function with the compiled one.
1593               ;;
1594               #+ecmalisp (set-binding-value macro-binding compiled)
1595               (setq expander compiled)))
1596           (apply expander (cdr form)))
1597         form)))
1598
1599 (defun compile-funcall (function args)
1600   (if (and (symbolp function)
1601            (claimp function 'function 'non-overridable))
1602       (concat (ls-compile `',function) ".function("
1603               (join (mapcar #'ls-compile args)
1604                     ", ")
1605               ")")
1606       (concat (ls-compile `#',function) "("
1607               (join (mapcar #'ls-compile args)
1608                     ", ")
1609               ")")))
1610
1611 (defun ls-compile-block (sexps &optional return-last-p)
1612   (if return-last-p
1613       (concat (ls-compile-block (butlast sexps))
1614               "return " (ls-compile (car (last sexps))) ";")
1615       (join-trailing
1616        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1617        (concat ";" *newline*))))
1618
1619 (defun ls-compile (sexp)
1620   (cond
1621     ((symbolp sexp)
1622      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1623        (cond
1624          ((eq (binding-type b) 'lexical-variable)
1625           (binding-value b))
1626          ((claimp sexp 'variable 'constant)
1627           (concat (ls-compile `',sexp) ".value"))
1628          (t
1629           (ls-compile `(symbol-value ',sexp))))))
1630     ((integerp sexp) (integer-to-string sexp))
1631     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1632     ((listp sexp)
1633      (let ((name (car sexp))
1634            (args (cdr sexp)))
1635        (cond
1636          ;; Special forms
1637          ((assoc name *compilations*)
1638           (let ((comp (second (assoc name *compilations*))))
1639             (apply comp args)))
1640          ;; Built-in functions
1641          ((and (assoc name *builtins*)
1642                (not (claimp name 'function 'notinline)))
1643           (let ((comp (second (assoc name *builtins*))))
1644             (apply comp args)))
1645          (t
1646           (if (macro name)
1647               (ls-compile (ls-macroexpand-1 sexp))
1648               (compile-funcall name args))))))))
1649
1650 (defun ls-compile-toplevel (sexp)
1651   (let ((*toplevel-compilations* nil))
1652     (cond
1653       ((and (consp sexp) (eq (car sexp) 'progn))
1654        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1655          (join (remove-if #'null-or-empty-p subs))))
1656       (t
1657        (let ((code (ls-compile sexp)))
1658          (concat (join-trailing (get-toplevel-compilations)
1659                                 (concat ";" *newline*))
1660                  (if code
1661                      (concat code ";" *newline*)
1662                      "")))))))
1663
1664
1665 ;;; Once we have the compiler, we define the runtime environment and
1666 ;;; interactive development (eval), which works calling the compiler
1667 ;;; and evaluating the Javascript result globally.
1668
1669 #+ecmalisp
1670 (progn
1671   (defmacro with-compilation-unit (&body body)
1672     `(prog1
1673          (progn
1674            (setq *compilation-unit-checks* nil)
1675            ,@body)
1676        (dolist (check *compilation-unit-checks*)
1677          (funcall check))))
1678
1679   (defun eval (x)
1680     (let ((code
1681            (with-compilation-unit
1682                (ls-compile-toplevel x))))
1683       (js-eval code)))
1684
1685   (js-eval "var lisp")
1686   (js-vset "lisp" (new))
1687   (js-vset "lisp.read" #'ls-read-from-string)
1688   (js-vset "lisp.print" #'prin1-to-string)
1689   (js-vset "lisp.eval" #'eval)
1690   (js-vset "lisp.compile" #'ls-compile-toplevel)
1691   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1692   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1693
1694   ;; Set the initial global environment to be equal to the host global
1695   ;; environment at this point of the compilation.
1696   (eval-when-compile
1697     (toplevel-compilation
1698      (ls-compile
1699       `(progn
1700          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1701                    *literal-symbols*)
1702          (setq *literal-symbols* ',*literal-symbols*)
1703          (setq *environment* ',*environment*)
1704          (setq *variable-counter* ,*variable-counter*)
1705          (setq *gensym-counter* ,*gensym-counter*)
1706          (setq *block-counter* ,*block-counter*)))))
1707
1708   (eval-when-compile
1709     (toplevel-compilation
1710      (ls-compile
1711       `(setq *literal-counter* ,*literal-counter*)))))
1712
1713
1714 ;;; Finally, we provide a couple of functions to easily bootstrap
1715 ;;; this. It just calls the compiler with this file as input.
1716
1717 #+common-lisp
1718 (progn
1719   (defun read-whole-file (filename)
1720     (with-open-file (in filename)
1721       (let ((seq (make-array (file-length in) :element-type 'character)))
1722         (read-sequence seq in)
1723         seq)))
1724
1725   (defun ls-compile-file (filename output)
1726     (setq *compilation-unit-checks* nil)
1727     (with-open-file (out output :direction :output :if-exists :supersede)
1728       (let* ((source (read-whole-file filename))
1729              (in (make-string-stream source)))
1730         (loop
1731            for x = (ls-read in)
1732            until (eq x *eof*)
1733            for compilation = (ls-compile-toplevel x)
1734            when (plusp (length compilation))
1735            do (write-string compilation out))
1736         (dolist (check *compilation-unit-checks*)
1737           (funcall check))
1738         (setq *compilation-unit-checks* nil))))
1739
1740   (defun bootstrap ()
1741     (setq *environment* (make-lexenv))
1742     (setq *literal-symbols* nil)
1743     (setq *variable-counter* 0
1744           *gensym-counter* 0
1745           *literal-counter* 0
1746           *block-counter* 0)
1747     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))