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