231787200a1add5ca299f33629a208ff2fcf524b
[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 symbols (symbol-name symbol) symbol)))
497
498   (defun intern (name &optional (package *package*))
499     (let ((symbols (%package-symbols package)))
500       (if (in name symbols)
501           (oget symbols name)
502           (oset symbols name (make-symbol name)))))
503
504   (defun find-symbol (name &optional (package *package*))
505     (let ((symbols (%package-symbols package)))
506       (oget *package* name))))
507
508
509
510 ;;; The compiler offers some primitives and special forms which are
511 ;;; not found in Common Lisp, for instance, while. So, we grow Common
512 ;;; Lisp a bit to it can execute the rest of the file.
513 #+common-lisp
514 (progn
515   (defmacro while (condition &body body)
516     `(do ()
517          ((not ,condition))
518        ,@body))
519
520   (defmacro eval-when-compile (&body body)
521     `(eval-when (:compile-toplevel :load-toplevel :execute)
522        ,@body))
523
524   (defun concat-two (s1 s2)
525     (concatenate 'string s1 s2))
526
527   (defun setcar (cons new)
528     (setf (car cons) new))
529   (defun setcdr (cons new)
530     (setf (cdr cons) new)))
531
532 ;;; At this point, no matter if Common Lisp or ecmalisp is compiling
533 ;;; from here, this code will compile on both. We define some helper
534 ;;; functions now for string manipulation and so on. They will be
535 ;;; useful in the compiler, mostly.
536
537 (defvar *newline* (string (code-char 10)))
538
539 (defun concat (&rest strs)
540   (!reduce #'concat-two strs ""))
541
542 (defmacro concatf (variable &body form)
543   `(setq ,variable (concat ,variable (progn ,@form))))
544
545 ;;; Concatenate a list of strings, with a separator
546 (defun join (list &optional (separator ""))
547   (cond
548     ((null list)
549      "")
550     ((null (cdr list))
551      (car list))
552     (t
553      (concat (car list)
554              separator
555              (join (cdr list) separator)))))
556
557 (defun join-trailing (list &optional (separator ""))
558   (if (null list)
559       ""
560       (concat (car list) separator (join-trailing (cdr list) separator))))
561
562 (defun mapconcat (func list)
563   (join (mapcar func list)))
564
565 ;;; Like CONCAT, but prefix each line with four spaces. Two versions
566 ;;; of this function are available, because the Ecmalisp version is
567 ;;; very slow and bootstraping was annoying.
568
569 #+ecmalisp
570 (defun indent (&rest string)
571   (let ((input (join string)))
572     (let ((output "")
573           (index 0)
574           (size (length input)))
575       (when (plusp (length input)) (concatf output "    "))
576       (while (< index size)
577         (let ((str
578                (if (and (char= (char input index) #\newline)
579                         (< index (1- size))
580                         (not (char= (char input (1+ index)) #\newline)))
581                    (concat (string #\newline) "    ")
582                    (string (char input index)))))
583           (concatf output str))
584         (incf index))
585       output)))
586
587 #+common-lisp
588 (defun indent (&rest string)
589   (with-output-to-string (*standard-output*)
590     (with-input-from-string (input (join string))
591       (loop
592          for line = (read-line input nil)
593          while line
594          do (write-string "    ")
595          do (write-line line)))))
596
597
598 (defun integer-to-string (x)
599   (cond
600     ((zerop x)
601      "0")
602     ((minusp x)
603      (concat "-" (integer-to-string (- 0 x))))
604     (t
605      (let ((digits nil))
606        (while (not (zerop x))
607          (push (mod x 10) digits)
608          (setq x (truncate x 10)))
609        (join (mapcar (lambda (d) (string (char "0123456789" d)))
610                      digits))))))
611
612
613 ;;; Wrap X with a Javascript code to convert the result from
614 ;;; Javascript generalized booleans to T or NIL.
615 (defun js!bool (x)
616   (concat "(" x "?" (ls-compile t) ": " (ls-compile nil) ")"))
617
618 ;;; Concatenate the arguments and wrap them with a self-calling
619 ;;; Javascript anonymous function. It is used to make some Javascript
620 ;;; statements valid expressions and provide a private scope as well.
621 ;;; It could be defined as function, but we could do some
622 ;;; preprocessing in the future.
623 (defmacro js!selfcall (&body body)
624   `(concat "(function(){" *newline* (indent ,@body) "})()"))
625
626
627 ;;; Printer
628
629 #+ecmalisp
630 (progn
631   (defun prin1-to-string (form)
632     (cond
633       ((symbolp form) (symbol-name form))
634       ((integerp form) (integer-to-string form))
635       ((stringp form) (concat "\"" (escape-string form) "\""))
636       ((functionp form)
637        (let ((name (oget form "fname")))
638          (if name
639              (concat "#<FUNCTION " name ">")
640              (concat "#<FUNCTION>"))))
641       ((listp form)
642        (concat "("
643                (join-trailing (mapcar #'prin1-to-string (butlast form)) " ")
644                (let ((last (last form)))
645                  (if (null (cdr last))
646                      (prin1-to-string (car last))
647                      (concat (prin1-to-string (car last)) " . " (prin1-to-string (cdr last)))))
648                ")"))
649       ((packagep form)
650        (concat "#<PACKAGE " (package-name form) ">"))))
651
652   (defun write-line (x)
653     (write-string x)
654     (write-string *newline*)
655     x)
656
657   (defun warn (string)
658     (write-string "WARNING: ")
659     (write-line string))
660
661   (defun print (x)
662     (write-line (prin1-to-string x))
663     x))
664
665
666 ;;;; Reader
667
668 ;;; The Lisp reader, parse strings and return Lisp objects. The main
669 ;;; entry points are `ls-read' and `ls-read-from-string'.
670
671 (defun make-string-stream (string)
672   (cons string 0))
673
674 (defun %peek-char (stream)
675   (and (< (cdr stream) (length (car stream)))
676        (char (car stream) (cdr stream))))
677
678 (defun %read-char (stream)
679   (and (< (cdr stream) (length (car stream)))
680        (prog1 (char (car stream) (cdr stream))
681          (setcdr stream (1+ (cdr stream))))))
682
683 (defun whitespacep (ch)
684   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
685
686 (defun skip-whitespaces (stream)
687   (let (ch)
688     (setq ch (%peek-char stream))
689     (while (and ch (whitespacep ch))
690       (%read-char stream)
691       (setq ch (%peek-char stream)))))
692
693 (defun terminalp (ch)
694   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
695
696 (defun read-until (stream func)
697   (let ((string "")
698         (ch))
699     (setq ch (%peek-char stream))
700     (while (and ch (not (funcall func ch)))
701       (setq string (concat string (string ch)))
702       (%read-char stream)
703       (setq ch (%peek-char stream)))
704     string))
705
706 (defun skip-whitespaces-and-comments (stream)
707   (let (ch)
708     (skip-whitespaces stream)
709     (setq ch (%peek-char stream))
710     (while (and ch (char= ch #\;))
711       (read-until stream (lambda (x) (char= x #\newline)))
712       (skip-whitespaces stream)
713       (setq ch (%peek-char stream)))))
714
715 (defun %read-list (stream)
716   (skip-whitespaces-and-comments stream)
717   (let ((ch (%peek-char stream)))
718     (cond
719       ((null ch)
720        (error "Unspected EOF"))
721       ((char= ch #\))
722        (%read-char stream)
723        nil)
724       ((char= ch #\.)
725        (%read-char stream)
726        (prog1 (ls-read stream)
727          (skip-whitespaces-and-comments stream)
728          (unless (char= (%read-char stream) #\))
729            (error "')' was expected."))))
730       (t
731        (cons (ls-read stream) (%read-list stream))))))
732
733 (defun read-string (stream)
734   (let ((string "")
735         (ch nil))
736     (setq ch (%read-char stream))
737     (while (not (eql ch #\"))
738       (when (null ch)
739         (error "Unexpected EOF"))
740       (when (eql ch #\\)
741         (setq ch (%read-char stream)))
742       (setq string (concat string (string ch)))
743       (setq ch (%read-char stream)))
744     string))
745
746 (defun read-sharp (stream)
747   (%read-char stream)
748   (ecase (%read-char stream)
749     (#\'
750      (list 'function (ls-read stream)))
751     (#\\
752      (let ((cname
753             (concat (string (%read-char stream))
754                     (read-until stream #'terminalp))))
755        (cond
756          ((string= cname "space") (char-code #\space))
757          ((string= cname "tab") (char-code #\tab))
758          ((string= cname "newline") (char-code #\newline))
759          (t (char-code (char cname 0))))))
760     (#\+
761      (let ((feature (read-until stream #'terminalp)))
762        (cond
763          ((string= feature "common-lisp")
764           (ls-read stream)              ;ignore
765           (ls-read stream))
766          ((string= feature "ecmalisp")
767           (ls-read stream))
768          (t
769           (error "Unknown reader form.")))))))
770
771 (defvar *eof* (make-symbol "EOF"))
772 (defun ls-read (stream)
773   (skip-whitespaces-and-comments stream)
774   (let ((ch (%peek-char stream)))
775     (cond
776       ((null ch)
777        *eof*)
778       ((char= ch #\()
779        (%read-char stream)
780        (%read-list stream))
781       ((char= ch #\')
782        (%read-char stream)
783        (list 'quote (ls-read stream)))
784       ((char= ch #\`)
785        (%read-char stream)
786        (list 'backquote (ls-read stream)))
787       ((char= ch #\")
788        (%read-char stream)
789        (read-string stream))
790       ((char= ch #\,)
791        (%read-char stream)
792        (if (eql (%peek-char stream) #\@)
793            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
794            (list 'unquote (ls-read stream))))
795       ((char= ch #\#)
796        (read-sharp stream))
797       (t
798        (let ((string (read-until stream #'terminalp)))
799          (if (every #'digit-char-p string)
800              (parse-integer string)
801              (intern (string-upcase string))))))))
802
803 (defun ls-read-from-string (string)
804   (ls-read (make-string-stream string)))
805
806
807 ;;;; Compiler
808
809 ;;; Translate the Lisp code to Javascript. It will compile the special
810 ;;; forms. Some primitive functions are compiled as special forms
811 ;;; too. The respective real functions are defined in the target (see
812 ;;; the beginning of this file) as well as some primitive functions.
813
814 (defvar *compilation-unit-checks* '())
815
816 (defun make-binding (name type value &optional declarations)
817   (list name type value declarations))
818
819 (defun binding-name (b) (first b))
820 (defun binding-type (b) (second b))
821 (defun binding-value (b) (third b))
822 (defun binding-declarations (b) (fourth b))
823
824 (defun set-binding-value (b value)
825   (setcar (cddr b) value))
826
827 (defun set-binding-declarations (b value)
828   (setcar (cdddr b) value))
829
830 (defun push-binding-declaration (decl b)
831   (set-binding-declarations b (cons decl (binding-declarations b))))
832
833
834 (defun make-lexenv ()
835   (list nil nil nil nil))
836
837 (defun copy-lexenv (lexenv)
838   (copy-list lexenv))
839
840 (defun push-to-lexenv (binding lexenv namespace)
841   (ecase namespace
842     (variable   (setcar        lexenv  (cons binding (car lexenv))))
843     (function   (setcar   (cdr lexenv) (cons binding (cadr lexenv))))
844     (block      (setcar  (cddr lexenv) (cons binding (caddr lexenv))))
845     (gotag      (setcar (cdddr lexenv) (cons binding (cadddr lexenv))))))
846
847 (defun extend-lexenv (bindings lexenv namespace)
848   (let ((env (copy-lexenv lexenv)))
849     (dolist (binding (reverse bindings) env)
850       (push-to-lexenv binding env namespace))))
851
852 (defun lookup-in-lexenv (name lexenv namespace)
853   (assoc name (ecase namespace
854                 (variable (first lexenv))
855                 (function (second lexenv))
856                 (block (third lexenv))
857                 (gotag (fourth lexenv)))))
858
859 (defvar *environment* (make-lexenv))
860
861 (defvar *variable-counter* 0)
862 (defun gvarname (symbol)
863   (concat "v" (integer-to-string (incf *variable-counter*))))
864
865 (defun translate-variable (symbol)
866   (binding-value (lookup-in-lexenv symbol *environment* 'variable)))
867
868 (defun extend-local-env (args)
869   (let ((new (copy-lexenv *environment*)))
870     (dolist (symbol args new)
871       (let ((b (make-binding symbol 'lexical-variable (gvarname symbol))))
872         (push-to-lexenv b new 'variable)))))
873
874 ;;; Toplevel compilations
875 (defvar *toplevel-compilations* nil)
876
877 (defun toplevel-compilation (string)
878   (push string *toplevel-compilations*))
879
880 (defun null-or-empty-p (x)
881   (zerop (length x)))
882
883 (defun get-toplevel-compilations ()
884   (reverse (remove-if #'null-or-empty-p *toplevel-compilations*)))
885
886 (defun %compile-defmacro (name lambda)
887   (toplevel-compilation (ls-compile `',name))
888   (push-to-lexenv (make-binding name 'macro lambda) *environment* 'function))
889
890 (defun global-binding (name type namespace)
891   (or (lookup-in-lexenv name *environment* namespace)
892       (let ((b (make-binding name type nil)))
893         (push-to-lexenv b *environment* namespace)
894         b)))
895
896 (defun claimp (symbol namespace claim)
897   (let ((b (lookup-in-lexenv symbol *environment* namespace)))
898     (and b (member claim (binding-declarations b)))))
899
900 (defun !proclaim (decl)
901   (case (car decl)
902     (notinline
903      (dolist (name (cdr decl))
904        (let ((b (global-binding name 'function 'function)))
905          (push-binding-declaration 'notinline b))))
906     (constant
907      (dolist (name (cdr decl))
908        (let ((b (global-binding name 'variable 'variable)))
909          (push-binding-declaration 'constant b))))
910     (non-overridable
911      (dolist (name (cdr decl))
912        (let ((b (global-binding name 'function 'function)))
913          (push-binding-declaration 'non-overridable b))))))
914
915
916 ;;; Special forms
917
918 (defvar *compilations* nil)
919
920 (defmacro define-compilation (name args &body body)
921   ;; Creates a new primitive `name' with parameters args and
922   ;; @body. The body can access to the local environment through the
923   ;; variable *ENVIRONMENT*.
924   `(push (list ',name (lambda ,args (block ,name ,@body)))
925          *compilations*))
926
927 (define-compilation if (condition true false)
928   (concat "(" (ls-compile condition) " !== " (ls-compile nil)
929           " ? " (ls-compile true)
930           " : " (ls-compile false)
931           ")"))
932
933 (defvar *lambda-list-keywords* '(&optional &rest))
934
935 (defun list-until-keyword (list)
936   (if (or (null list) (member (car list) *lambda-list-keywords*))
937       nil
938       (cons (car list) (list-until-keyword (cdr list)))))
939
940 (defun lambda-list-required-arguments (lambda-list)
941   (list-until-keyword lambda-list))
942
943 (defun lambda-list-optional-arguments-with-default (lambda-list)
944   (mapcar #'ensure-list (list-until-keyword (cdr (member '&optional lambda-list)))))
945
946 (defun lambda-list-optional-arguments (lambda-list)
947   (mapcar #'car (lambda-list-optional-arguments-with-default lambda-list)))
948
949 (defun lambda-list-rest-argument (lambda-list)
950   (let ((rest (list-until-keyword (cdr (member '&rest lambda-list)))))
951     (when (cdr rest)
952       (error "Bad lambda-list"))
953     (car rest)))
954
955
956 (defun lambda-docstring-wrapper (docstring &rest strs)
957   (if docstring
958       (js!selfcall
959         "var func = " (join strs) ";" *newline*
960         "func.docstring = '" docstring "';" *newline*
961         "return func;" *newline*)
962       (join strs)))
963
964 (define-compilation lambda (lambda-list &rest body)
965   (let ((required-arguments (lambda-list-required-arguments lambda-list))
966         (optional-arguments (lambda-list-optional-arguments lambda-list))
967         (rest-argument (lambda-list-rest-argument lambda-list))
968         documentation)
969     ;; Get the documentation string for the lambda function
970     (when (and (stringp (car body))
971                (not (null (cdr body))))
972       (setq documentation (car body))
973       (setq body (cdr body)))
974     (let ((n-required-arguments (length required-arguments))
975           (n-optional-arguments (length optional-arguments))
976           (*environment* (extend-local-env
977                           (append (ensure-list rest-argument)
978                                   required-arguments
979                                   optional-arguments))))
980       (lambda-docstring-wrapper
981        documentation
982        "(function ("
983        (join (mapcar #'translate-variable
984                      (append required-arguments optional-arguments))
985              ",")
986        "){" *newline*
987        ;; Check number of arguments
988        (indent
989         (if required-arguments
990             (concat "if (arguments.length < " (integer-to-string n-required-arguments)
991                     ") throw 'too few arguments';" *newline*)
992             "")
993         (if (not rest-argument)
994             (concat "if (arguments.length > "
995                     (integer-to-string (+ n-required-arguments n-optional-arguments))
996                     ") throw 'too many arguments';" *newline*)
997             "")
998         ;; Optional arguments
999         (if optional-arguments
1000             (concat "switch(arguments.length){" *newline*
1001                     (let ((optional-and-defaults
1002                            (lambda-list-optional-arguments-with-default lambda-list))
1003                           (cases nil)
1004                           (idx 0))
1005                       (progn
1006                         (while (< idx n-optional-arguments)
1007                           (let ((arg (nth idx optional-and-defaults)))
1008                             (push (concat "case "
1009                                           (integer-to-string (+ idx n-required-arguments)) ":" *newline*
1010                                           (translate-variable (car arg))
1011                                           "="
1012                                           (ls-compile (cadr arg))
1013                                           ";" *newline*)
1014                                   cases)
1015                             (incf idx)))
1016                         (push (concat "default: break;" *newline*) cases)
1017                         (join (reverse cases))))
1018                     "}" *newline*)
1019             "")
1020         ;; &rest/&body argument
1021         (if rest-argument
1022             (let ((js!rest (translate-variable rest-argument)))
1023               (concat "var " js!rest "= " (ls-compile nil) ";" *newline*
1024                       "for (var i = arguments.length-1; i>="
1025                       (integer-to-string (+ n-required-arguments n-optional-arguments))
1026                       "; i--)" *newline*
1027                       (indent js!rest " = "
1028                               "{car: arguments[i], cdr: ") js!rest "};"
1029                       *newline*))
1030             "")
1031         ;; Body
1032         (ls-compile-block body t)) *newline*
1033        "})"))))
1034
1035 (define-compilation setq (var val)
1036   (let ((b (lookup-in-lexenv var *environment* 'variable)))
1037     (if (eq (binding-type b) 'lexical-variable)
1038         (concat (binding-value b) " = " (ls-compile val))
1039         (ls-compile `(set ',var ,val)))))
1040
1041 ;;; FFI Variable accessors
1042 (define-compilation js-vref (var)
1043   var)
1044
1045 (define-compilation js-vset (var val)
1046   (concat "(" var " = " (ls-compile val) ")"))
1047
1048
1049 ;;; Literals
1050 (defun escape-string (string)
1051   (let ((output "")
1052         (index 0)
1053         (size (length string)))
1054     (while (< index size)
1055       (let ((ch (char string index)))
1056         (when (or (char= ch #\") (char= ch #\\))
1057           (setq output (concat output "\\")))
1058         (when (or (char= ch #\newline))
1059           (setq output (concat output "\\"))
1060           (setq ch #\n))
1061         (setq output (concat output (string ch))))
1062       (incf index))
1063     output))
1064
1065
1066 (defvar *literal-symbols* nil)
1067 (defvar *literal-counter* 0)
1068
1069 (defun genlit ()
1070   (concat "l" (integer-to-string (incf *literal-counter*))))
1071
1072 (defun literal (sexp &optional recursive)
1073   (cond
1074     ((integerp sexp) (integer-to-string sexp))
1075     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1076     ((symbolp sexp)
1077      (or (cdr (assoc sexp *literal-symbols*))
1078          (let ((v (genlit))
1079                (s #+common-lisp (concat "{name: \"" (escape-string (symbol-name sexp)) "\"}")
1080                   #+ecmalisp (ls-compile `(intern ,(symbol-name sexp)))))
1081            (push (cons sexp v) *literal-symbols*)
1082            (toplevel-compilation (concat "var " v " = " s))
1083            v)))
1084     ((consp sexp)
1085      (let ((c (concat "{car: " (literal (car sexp) t) ", "
1086                       "cdr: " (literal (cdr sexp) t) "}")))
1087        (if recursive
1088            c
1089            (let ((v (genlit)))
1090              (toplevel-compilation (concat "var " v " = " c))
1091              v))))))
1092
1093 (define-compilation quote (sexp)
1094   (literal sexp))
1095
1096 (define-compilation %while (pred &rest body)
1097   (js!selfcall
1098     "while(" (ls-compile pred) " !== " (ls-compile nil) "){" *newline*
1099     (indent (ls-compile-block body))
1100     "}"
1101     "return " (ls-compile nil) ";" *newline*))
1102
1103 (define-compilation function (x)
1104   (cond
1105     ((and (listp x) (eq (car x) 'lambda))
1106      (ls-compile x))
1107     ((symbolp x)
1108      (ls-compile `(symbol-function ',x)))))
1109
1110 (define-compilation eval-when-compile (&rest body)
1111   (eval (cons 'progn body))
1112   nil)
1113
1114 (defmacro define-transformation (name args form)
1115   `(define-compilation ,name ,args
1116      (ls-compile ,form)))
1117
1118 (define-compilation progn (&rest body)
1119   (js!selfcall (ls-compile-block body t)))
1120
1121 (defun dynamic-binding-wrapper (bindings body)
1122   (if (null bindings)
1123       body
1124       (concat
1125        "try {" *newline*
1126        (indent
1127         "var tmp;" *newline*
1128         (join
1129          (mapcar (lambda (b)
1130                    (let ((s (ls-compile `(quote ,(car b)))))
1131                      (concat "tmp = " s ".value;" *newline*
1132                              s ".value = " (cdr b) ";" *newline*
1133                              (cdr b) " = tmp;" *newline*)))
1134                  bindings))
1135         body)
1136        "}" *newline*
1137        "finally {"  *newline*
1138        (indent
1139         (join-trailing
1140          (mapcar (lambda (b)
1141                    (let ((s (ls-compile `(quote ,(car b)))))
1142                      (concat s ".value" " = " (cdr b))))
1143                  bindings)
1144          (concat ";" *newline*)))
1145        "}" *newline*)))
1146
1147
1148 (define-compilation let (bindings &rest body)
1149   (let ((bindings (mapcar #'ensure-list bindings)))
1150     (let ((variables (mapcar #'first bindings))
1151           (values    (mapcar #'second bindings)))
1152       (let ((cvalues (mapcar #'ls-compile values))
1153             (*environment* (extend-local-env (remove-if #'boundp variables)))
1154             (dynamic-bindings))
1155         (concat "(function("
1156                 (join (mapcar (lambda (x)
1157                                 (if (boundp x)
1158                                     (let ((v (gvarname x)))
1159                                       (push (cons x v) dynamic-bindings)
1160                                       v)
1161                                     (translate-variable x)))
1162                               variables)
1163                       ",")
1164                 "){" *newline*
1165                 (let ((body (ls-compile-block body t)))
1166                   (indent (dynamic-binding-wrapper dynamic-bindings body)))
1167                 "})(" (join cvalues ",") ")")))))
1168
1169
1170 (defvar *block-counter* 0)
1171
1172 (define-compilation block (name &rest body)
1173   (let ((tr (integer-to-string (incf *block-counter*))))
1174     (let ((b (make-binding name 'block tr)))
1175       (js!selfcall
1176         "try {" *newline*
1177         (let ((*environment* (extend-lexenv (list b) *environment* 'block)))
1178           (indent "return " (ls-compile `(progn ,@body)) ";" *newline*))
1179         "}" *newline*
1180         "catch (cf){" *newline*
1181         "    if (cf.type == 'block' && cf.id == " tr ")" *newline*
1182         "        return cf.value;" *newline*
1183         "    else" *newline*
1184         "        throw cf;" *newline*
1185         "}" *newline*))))
1186
1187 (define-compilation return-from (name &optional value)
1188   (let ((b (lookup-in-lexenv name *environment* 'block)))
1189     (if b
1190         (js!selfcall
1191           "throw ({"
1192           "type: 'block', "
1193           "id: " (binding-value b) ", "
1194           "value: " (ls-compile value) ", "
1195           "message: 'Return from unknown block " (symbol-name name) ".'"
1196           "})")
1197         (error (concat "Unknown block `" (symbol-name name) "'.")))))
1198
1199
1200 (define-compilation catch (id &rest body)
1201   (js!selfcall
1202     "var id = " (ls-compile id) ";" *newline*
1203     "try {" *newline*
1204     (indent "return " (ls-compile `(progn ,@body))
1205             ";" *newline*)
1206     "}" *newline*
1207     "catch (cf){" *newline*
1208     "    if (cf.type == 'catch' && cf.id == id)" *newline*
1209     "        return cf.value;" *newline*
1210     "    else" *newline*
1211     "        throw cf;" *newline*
1212     "}" *newline*))
1213
1214 (define-compilation throw (id &optional value)
1215   (js!selfcall
1216     "throw ({"
1217     "type: 'catch', "
1218     "id: " (ls-compile id) ", "
1219     "value: " (ls-compile value) ", "
1220     "message: 'Throw uncatched.'"
1221     "})"))
1222
1223
1224 (defvar *tagbody-counter* 0)
1225 (defvar *go-tag-counter* 0)
1226
1227 (defun go-tag-p (x)
1228   (or (integerp x) (symbolp x)))
1229
1230 (defun declare-tagbody-tags (tbidx body)
1231   (let ((bindings
1232          (mapcar (lambda (label)
1233                    (let ((tagidx (integer-to-string (incf *go-tag-counter*))))
1234                      (make-binding label 'gotag (list tbidx tagidx))))
1235                  (remove-if-not #'go-tag-p body))))
1236     (extend-lexenv bindings *environment* 'gotag)))
1237
1238 (define-compilation tagbody (&rest body)
1239   ;; Ignore the tagbody if it does not contain any go-tag. We do this
1240   ;; because 1) it is easy and 2) many built-in forms expand to a
1241   ;; implicit tagbody, so we save some space.
1242   (unless (some #'go-tag-p body)
1243     (return-from tagbody (ls-compile `(progn ,@body nil))))
1244   ;; The translation assumes the first form in BODY is a label
1245   (unless (go-tag-p (car body))
1246     (push (gensym "START") body))
1247   ;; Tagbody compilation
1248   (let ((tbidx (integer-to-string *tagbody-counter*)))
1249     (let ((*environment* (declare-tagbody-tags tbidx body))
1250           initag)
1251       (let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
1252         (setq initag (second (binding-value b))))
1253       (js!selfcall
1254         "var tagbody_" tbidx " = " initag ";" *newline*
1255         "tbloop:" *newline*
1256         "while (true) {" *newline*
1257         (indent "try {" *newline*
1258                 (indent (let ((content ""))
1259                           (concat "switch(tagbody_" tbidx "){" *newline*
1260                                   "case " initag ":" *newline*
1261                                   (dolist (form (cdr body) content)
1262                                     (concatf content
1263                                       (if (not (go-tag-p form))
1264                                           (indent (ls-compile form) ";" *newline*)
1265                                           (let ((b (lookup-in-lexenv form *environment* 'gotag)))
1266                                             (concat "case " (second (binding-value b)) ":" *newline*)))))
1267                                   "default:" *newline*
1268                                   "    break tbloop;" *newline*
1269                                   "}" *newline*)))
1270                 "}" *newline*
1271                 "catch (jump) {" *newline*
1272                 "    if (jump.type == 'tagbody' && jump.id == " tbidx ")" *newline*
1273                 "        tagbody_" tbidx " = jump.label;" *newline*
1274                 "    else" *newline*
1275                 "        throw(jump);" *newline*
1276                 "}" *newline*)
1277         "}" *newline*
1278         "return " (ls-compile nil) ";" *newline*))))
1279
1280 (define-compilation go (label)
1281   (let ((b (lookup-in-lexenv label *environment* 'gotag))
1282         (n (cond
1283              ((symbolp label) (symbol-name label))
1284              ((integerp label) (integer-to-string label)))))
1285     (if b
1286         (js!selfcall
1287           "throw ({"
1288           "type: 'tagbody', "
1289           "id: " (first (binding-value b)) ", "
1290           "label: " (second (binding-value b)) ", "
1291           "message: 'Attempt to GO to non-existing tag " n "'"
1292           "})" *newline*)
1293         (error (concat "Unknown tag `" n "'.")))))
1294
1295
1296 (define-compilation unwind-protect (form &rest clean-up)
1297   (js!selfcall
1298     "var ret = " (ls-compile nil) ";" *newline*
1299     "try {" *newline*
1300     (indent "ret = " (ls-compile form) ";" *newline*)
1301     "} finally {" *newline*
1302     (indent (ls-compile-block clean-up))
1303     "}" *newline*
1304     "return ret;" *newline*))
1305
1306
1307 ;;; A little backquote implementation without optimizations of any
1308 ;;; kind for ecmalisp.
1309 (defun backquote-expand-1 (form)
1310   (cond
1311     ((symbolp form)
1312      (list 'quote form))
1313     ((atom form)
1314      form)
1315     ((eq (car form) 'unquote)
1316      (car form))
1317     ((eq (car form) 'backquote)
1318      (backquote-expand-1 (backquote-expand-1 (cadr form))))
1319     (t
1320      (cons 'append
1321            (mapcar (lambda (s)
1322                      (cond
1323                        ((and (listp s) (eq (car s) 'unquote))
1324                         (list 'list (cadr s)))
1325                        ((and (listp s) (eq (car s) 'unquote-splicing))
1326                         (cadr s))
1327                        (t
1328                         (list 'list (backquote-expand-1 s)))))
1329                    form)))))
1330
1331 (defun backquote-expand (form)
1332   (if (and (listp form) (eq (car form) 'backquote))
1333       (backquote-expand-1 (cadr form))
1334       form))
1335
1336 (defmacro backquote (form)
1337   (backquote-expand-1 form))
1338
1339 (define-transformation backquote (form)
1340   (backquote-expand-1 form))
1341
1342 ;;; Primitives
1343
1344 (defvar *builtins* nil)
1345
1346 (defmacro define-raw-builtin (name args &body body)
1347   ;; Creates a new primitive function `name' with parameters args and
1348   ;; @body. The body can access to the local environment through the
1349   ;; variable *ENVIRONMENT*.
1350   `(push (list ',name (lambda ,args (block ,name ,@body)))
1351          *builtins*))
1352
1353 (defmacro define-builtin (name args &body body)
1354   `(progn
1355      (define-raw-builtin ,name ,args
1356        (let ,(mapcar (lambda (arg) `(,arg (ls-compile ,arg))) args)
1357          ,@body))))
1358
1359 ;;; DECLS is a list of (JSVARNAME TYPE LISPFORM) declarations.
1360 (defmacro type-check (decls &body body)
1361   `(js!selfcall
1362      ,@(mapcar (lambda (decl)
1363                    `(concat "var " ,(first decl) " = " ,(third decl) ";" *newline*))
1364                  decls)
1365      ,@(mapcar (lambda (decl)
1366                  `(concat "if (typeof " ,(first decl) " != '" ,(second decl) "')" *newline*
1367                           (indent "throw 'The value ' + "
1368                                   ,(first decl)
1369                                   " + ' is not a type "
1370                                   ,(second decl)
1371                                   ".';"
1372                                   *newline*)))
1373                decls)
1374      (concat "return " (progn ,@body) ";" *newline*)))
1375
1376 (defun num-op-num (x op y)
1377   (type-check (("x" "number" x) ("y" "number" y))
1378     (concat "x" op "y")))
1379
1380 (define-builtin + (x y) (num-op-num x "+" y))
1381 (define-builtin - (x y) (num-op-num x "-" y))
1382 (define-builtin * (x y) (num-op-num x "*" y))
1383 (define-builtin / (x y) (num-op-num x "/" y))
1384
1385 (define-builtin mod (x y) (num-op-num x "%" y))
1386
1387 (define-builtin < (x y)  (js!bool (num-op-num x "<" y)))
1388 (define-builtin > (x y)  (js!bool (num-op-num x ">" y)))
1389 (define-builtin = (x y)  (js!bool (num-op-num x "==" y)))
1390 (define-builtin <= (x y) (js!bool (num-op-num x "<=" y)))
1391 (define-builtin >= (x y) (js!bool (num-op-num x ">=" y)))
1392
1393 (define-builtin numberp (x)
1394   (js!bool (concat "(typeof (" x ") == \"number\")")))
1395
1396 (define-builtin floor (x)
1397   (type-check (("x" "number" x))
1398     "Math.floor(x)"))
1399
1400 (define-builtin cons (x y)
1401   (concat "({car: " x ", cdr: " y "})"))
1402
1403 (define-builtin consp (x)
1404   (js!bool
1405    (js!selfcall
1406      "var tmp = " x ";" *newline*
1407      "return (typeof tmp == 'object' && 'car' in tmp);" *newline*)))
1408
1409 (define-builtin car (x)
1410   (js!selfcall
1411     "var tmp = " x ";" *newline*
1412     "return tmp === " (ls-compile nil)
1413     "? " (ls-compile nil)
1414     ": tmp.car;" *newline*))
1415
1416 (define-builtin cdr (x)
1417   (js!selfcall
1418     "var tmp = " x ";" *newline*
1419     "return tmp === " (ls-compile nil) "? "
1420     (ls-compile nil)
1421     ": tmp.cdr;" *newline*))
1422
1423 (define-builtin setcar (x new)
1424   (type-check (("x" "object" x))
1425     (concat "(x.car = " new ")")))
1426
1427 (define-builtin setcdr (x new)
1428   (type-check (("x" "object" x))
1429     (concat "(x.cdr = " new ")")))
1430
1431 (define-builtin symbolp (x)
1432   (js!bool
1433    (js!selfcall
1434      "var tmp = " x ";" *newline*
1435      "return (typeof tmp == 'object' && 'name' in tmp);" *newline*)))
1436
1437 (define-builtin make-symbol (name)
1438   (type-check (("name" "string" name))
1439     "({name: name})"))
1440
1441 (define-builtin symbol-name (x)
1442   (concat "(" x ").name"))
1443
1444 (define-builtin set (symbol value)
1445   (concat "(" symbol ").value = " value))
1446
1447 (define-builtin fset (symbol value)
1448   (concat "(" symbol ").function = " value))
1449
1450 (define-builtin boundp (x)
1451   (js!bool (concat "(" x ".value !== undefined)")))
1452
1453 (define-builtin symbol-value (x)
1454   (js!selfcall
1455     "var symbol = " x ";" *newline*
1456     "var value = symbol.value;" *newline*
1457     "if (value === undefined) throw \"Variable `\" + symbol.name + \"' is unbound.\";" *newline*
1458     "return value;" *newline*))
1459
1460 (define-builtin symbol-function (x)
1461   (js!selfcall
1462     "var symbol = " x ";" *newline*
1463     "var func = symbol.function;" *newline*
1464     "if (func === undefined) throw \"Function `\" + symbol.name + \"' is undefined.\";" *newline*
1465     "return func;" *newline*))
1466
1467 (define-builtin symbol-plist (x)
1468   (concat "((" x ").plist || " (ls-compile nil) ")"))
1469
1470 (define-builtin lambda-code (x)
1471   (concat "(" x ").toString()"))
1472
1473
1474 (define-builtin eq    (x y) (js!bool (concat "(" x " === " y ")")))
1475 (define-builtin equal (x y) (js!bool (concat "(" x  " == " y ")")))
1476
1477 (define-builtin char-to-string (x)
1478   (type-check (("x" "number" x))
1479     "String.fromCharCode(x)"))
1480
1481 (define-builtin stringp (x)
1482   (js!bool (concat "(typeof(" x ") == \"string\")")))
1483
1484 (define-builtin string-upcase (x)
1485   (type-check (("x" "string" x))
1486     "x.toUpperCase()"))
1487
1488 (define-builtin string-length (x)
1489   (type-check (("x" "string" x))
1490     "x.length"))
1491
1492 (define-raw-builtin slice (string a &optional b)
1493   (js!selfcall
1494     "var str = " (ls-compile string) ";" *newline*
1495     "var a = " (ls-compile a) ";" *newline*
1496     "var b;" *newline*
1497     (if b
1498         (concat "b = " (ls-compile b) ";" *newline*)
1499         "")
1500     "return str.slice(a,b);" *newline*))
1501
1502 (define-builtin char (string index)
1503   (type-check (("string" "string" string)
1504                ("index" "number" index))
1505     "string.charCodeAt(index)"))
1506
1507 (define-builtin concat-two (string1 string2)
1508   (type-check (("string1" "string" string1)
1509                ("string2" "string" string2))
1510     "string1.concat(string2)"))
1511
1512 (define-raw-builtin funcall (func &rest args)
1513   (concat "(" (ls-compile func) ")("
1514           (join (mapcar #'ls-compile args)
1515                 ", ")
1516           ")"))
1517
1518 (define-raw-builtin apply (func &rest args)
1519   (if (null args)
1520       (concat "(" (ls-compile func) ")()")
1521       (let ((args (butlast args))
1522             (last (car (last args))))
1523         (js!selfcall
1524           "var f = " (ls-compile func) ";" *newline*
1525           "var args = [" (join (mapcar #'ls-compile args)
1526                                ", ")
1527           "];" *newline*
1528           "var tail = (" (ls-compile last) ");" *newline*
1529           "while (tail != " (ls-compile nil) "){" *newline*
1530           "    args.push(tail.car);" *newline*
1531           "    tail = tail.cdr;" *newline*
1532           "}" *newline*
1533           "return f.apply(this, args);" *newline*))))
1534
1535 (define-builtin js-eval (string)
1536   (type-check (("string" "string" string))
1537     "eval.apply(window, [string])"))
1538
1539 (define-builtin error (string)
1540   (js!selfcall "throw " string ";" *newline*))
1541
1542 (define-builtin new () "{}")
1543
1544 (define-builtin objectp (x)
1545   (js!bool (concat "(typeof (" x ") === 'object')")))
1546
1547 (define-builtin oget (object key)
1548   (js!selfcall
1549     "var tmp = " "(" object ")[" key "];" *newline*
1550     "return tmp == undefined? " (ls-compile nil) ": tmp ;" *newline*))
1551
1552 (define-builtin oset (object key value)
1553   (concat "((" object ")[" key "] = " value ")"))
1554
1555 (define-builtin in (key object)
1556   (js!bool (concat "((" key ") in (" object "))")))
1557
1558 (define-builtin functionp (x)
1559   (js!bool (concat "(typeof " x " == 'function')")))
1560
1561 (define-builtin write-string (x)
1562   (type-check (("x" "string" x))
1563     "lisp.write(x)"))
1564
1565 (defun macro (x)
1566   (and (symbolp x)
1567        (let ((b (lookup-in-lexenv x *environment* 'function)))
1568          (and (eq (binding-type b) 'macro)
1569               b))))
1570
1571 (defun ls-macroexpand-1 (form)
1572   (let ((macro-binding (macro (car form))))
1573     (if macro-binding
1574         (let ((expander (binding-value macro-binding)))
1575           (when (listp expander)
1576             (let ((compiled (eval expander)))
1577               ;; The list representation are useful while
1578               ;; bootstrapping, as we can dump the definition of the
1579               ;; macros easily, but they are slow because we have to
1580               ;; evaluate them and compile them now and again. So, let
1581               ;; us replace the list representation version of the
1582               ;; function with the compiled one.
1583               ;;
1584               #+ecmalisp (set-binding-value macro-binding compiled)
1585               (setq expander compiled)))
1586           (apply expander (cdr form)))
1587         form)))
1588
1589 (defun compile-funcall (function args)
1590   (if (and (symbolp function)
1591            (claimp function 'function 'non-overridable))
1592       (concat (ls-compile `',function) ".function("
1593               (join (mapcar #'ls-compile args)
1594                     ", ")
1595               ")")
1596       (concat (ls-compile `#',function) "("
1597               (join (mapcar #'ls-compile args)
1598                     ", ")
1599               ")")))
1600
1601 (defun ls-compile-block (sexps &optional return-last-p)
1602   (if return-last-p
1603       (concat (ls-compile-block (butlast sexps))
1604               "return " (ls-compile (car (last sexps))) ";")
1605       (join-trailing
1606        (remove-if #'null-or-empty-p (mapcar #'ls-compile sexps))
1607        (concat ";" *newline*))))
1608
1609 (defun ls-compile (sexp)
1610   (cond
1611     ((symbolp sexp)
1612      (let ((b (lookup-in-lexenv sexp *environment* 'variable)))
1613        (cond
1614          ((eq (binding-type b) 'lexical-variable)
1615           (binding-value b))
1616          ((claimp sexp 'variable 'constant)
1617           (concat (ls-compile `',sexp) ".value"))
1618          (t
1619           (ls-compile `(symbol-value ',sexp))))))
1620     ((integerp sexp) (integer-to-string sexp))
1621     ((stringp sexp) (concat "\"" (escape-string sexp) "\""))
1622     ((listp sexp)
1623      (let ((name (car sexp))
1624            (args (cdr sexp)))
1625        (cond
1626          ;; Special forms
1627          ((assoc name *compilations*)
1628           (let ((comp (second (assoc name *compilations*))))
1629             (apply comp args)))
1630          ;; Built-in functions
1631          ((and (assoc name *builtins*)
1632                (not (claimp name 'function 'notinline)))
1633           (let ((comp (second (assoc name *builtins*))))
1634             (apply comp args)))
1635          (t
1636           (if (macro name)
1637               (ls-compile (ls-macroexpand-1 sexp))
1638               (compile-funcall name args))))))))
1639
1640 (defun ls-compile-toplevel (sexp)
1641   (let ((*toplevel-compilations* nil))
1642     (cond
1643       ((and (consp sexp) (eq (car sexp) 'progn))
1644        (let ((subs (mapcar #'ls-compile-toplevel (cdr sexp))))
1645          (join (remove-if #'null-or-empty-p subs))))
1646       (t
1647        (let ((code (ls-compile sexp)))
1648          (concat (join-trailing (get-toplevel-compilations)
1649                                 (concat ";" *newline*))
1650                  (if code
1651                      (concat code ";" *newline*)
1652                      "")))))))
1653
1654
1655 ;;; Once we have the compiler, we define the runtime environment and
1656 ;;; interactive development (eval), which works calling the compiler
1657 ;;; and evaluating the Javascript result globally.
1658
1659 #+ecmalisp
1660 (progn
1661   (defmacro with-compilation-unit (&body body)
1662     `(prog1
1663          (progn
1664            (setq *compilation-unit-checks* nil)
1665            ,@body)
1666        (dolist (check *compilation-unit-checks*)
1667          (funcall check))))
1668
1669   (defun eval (x)
1670     (let ((code
1671            (with-compilation-unit
1672                (ls-compile-toplevel x))))
1673       (js-eval code)))
1674
1675   (js-eval "var lisp")
1676   (js-vset "lisp" (new))
1677   (js-vset "lisp.read" #'ls-read-from-string)
1678   (js-vset "lisp.print" #'prin1-to-string)
1679   (js-vset "lisp.eval" #'eval)
1680   (js-vset "lisp.compile" #'ls-compile-toplevel)
1681   (js-vset "lisp.evalString" (lambda (str) (eval (ls-read-from-string str))))
1682   (js-vset "lisp.compileString" (lambda (str) (ls-compile-toplevel (ls-read-from-string str))))
1683
1684   ;; Set the initial global environment to be equal to the host global
1685   ;; environment at this point of the compilation.
1686   (eval-when-compile
1687     (toplevel-compilation
1688      (ls-compile
1689       `(progn
1690          ,@(mapcar (lambda (s) `(%intern-symbol (js-vref ,(cdr s))))
1691                    *literal-symbols*)
1692          (setq *literal-symbols* ',*literal-symbols*)
1693          (setq *environment* ',*environment*)
1694          (setq *variable-counter* ,*variable-counter*)
1695          (setq *gensym-counter* ,*gensym-counter*)
1696          (setq *block-counter* ,*block-counter*)))))
1697
1698   (eval-when-compile
1699     (toplevel-compilation
1700      (ls-compile
1701       `(setq *literal-counter* ,*literal-counter*)))))
1702
1703
1704 ;;; Finally, we provide a couple of functions to easily bootstrap
1705 ;;; this. It just calls the compiler with this file as input.
1706
1707 #+common-lisp
1708 (progn
1709   (defun read-whole-file (filename)
1710     (with-open-file (in filename)
1711       (let ((seq (make-array (file-length in) :element-type 'character)))
1712         (read-sequence seq in)
1713         seq)))
1714
1715   (defun ls-compile-file (filename output)
1716     (setq *compilation-unit-checks* nil)
1717     (with-open-file (out output :direction :output :if-exists :supersede)
1718       (let* ((source (read-whole-file filename))
1719              (in (make-string-stream source)))
1720         (loop
1721            for x = (ls-read in)
1722            until (eq x *eof*)
1723            for compilation = (ls-compile-toplevel x)
1724            when (plusp (length compilation))
1725            do (write-string compilation out))
1726         (dolist (check *compilation-unit-checks*)
1727           (funcall check))
1728         (setq *compilation-unit-checks* nil))))
1729
1730   (defun bootstrap ()
1731     (setq *environment* (make-lexenv))
1732     (setq *literal-symbols* nil)
1733     (setq *variable-counter* 0
1734           *gensym-counter* 0
1735           *literal-counter* 0
1736           *block-counter* 0)
1737     (ls-compile-file "ecmalisp.lisp" "ecmalisp.js")))