a9fba973f69b2a334053416be4a579c00ff5a47b
[jscl.git] / lispstrack.lisp
1 (defun !reduce (func list initial)
2   (if (null list)
3       initial
4       (!reduce func
5                (cdr list)
6                (funcall func initial (car list)))))
7
8 ;;; Utils
9
10 #+common-lisp
11 (progn
12   (defmacro while (condition &body body)
13     `(do ()
14          ((not ,condition))
15        ,@body))
16
17   (defun concat-two (s1 s2)
18     (concatenate 'string s1 s2)))
19
20 (defvar *newline* (string (code-char 10)))
21
22 (defun concat (&rest strs)
23   (!reduce (lambda (s1 s2) (concat-two s1 s2))
24            strs
25            ""))
26
27 ;;; Concatenate a list of strings, with a separator
28 (defun join (list separator)
29   (cond
30     ((null list)
31      "")
32     ((null (cdr list))
33      (car list))
34     (t
35      (concat (car list)
36              separator
37              (join (cdr list) separator)))))
38
39 (defun join-trailing (list separator)
40   (if (null list)
41       ""
42       (concat (car list) separator (join-trailing (cdr list) separator))))
43
44 (defun integer-to-string (x)
45   (if (zerop x)
46       "0"
47       (let ((digits nil))
48         (while (not (= x 0))
49           (push (mod x 10) digits)
50           (setq x (truncate x 10)))
51         (join (mapcar (lambda (d) (string (char "0123456789" d)))
52                       digits)
53               ""))))
54
55 ;;;; Reader
56
57 ;;; It is a basic Lisp reader. It does not use advanced stuff
58 ;;; intentionally, because we want to use it to bootstrap a simple
59 ;;; Lisp. The main entry point is the function `ls-read', which
60 ;;; accepts a strings as argument and return the Lisp expression.
61 (defun make-string-stream (string)
62   (cons string 0))
63
64 (defun %peek-char (stream)
65   (if (streamp stream)
66       (peek-char nil stream nil)
67       (and (< (cdr stream) (length (car stream)))
68            (char (car stream) (cdr stream)))))
69
70 (defun %read-char (stream)
71   (if (streamp stream)
72       (read-char stream nil)
73       (and (< (cdr stream) (length (car stream)))
74            (prog1 (char (car stream) (cdr stream))
75              (incf (cdr stream))))))
76
77 (defun whitespacep (ch)
78   (or (char= ch #\space) (char= ch #\newline) (char= ch #\tab)))
79
80 (defun skip-whitespaces (stream)
81   (let (ch)
82     (setq ch (%peek-char stream))
83     (while (and ch (whitespacep ch))
84       (%read-char stream)
85       (setq ch (%peek-char stream)))))
86
87 (defun terminalp (ch)
88   (or (null ch) (whitespacep ch) (char= #\) ch) (char= #\( ch)))
89
90 (defun read-until (stream func)
91   (let ((string "")
92         (ch))
93     (setq ch (%peek-char stream))
94     (while (not (funcall func ch))
95       (setq string (concat string (string ch)))
96       (%read-char stream)
97       (setq ch (%peek-char stream)))
98     string))
99
100 (defun skip-whitespaces-and-comments (stream)
101   (let (ch)
102     (skip-whitespaces stream)
103     (setq ch (%peek-char stream))
104     (while (and ch (eql ch #\;))
105       (read-until stream (lambda (x) (eql x #\newline)))
106       (skip-whitespaces stream)
107       (setq ch (%peek-char stream)))))
108
109 (defun %read-list (stream)
110   (skip-whitespaces-and-comments stream)
111   (let ((ch (%peek-char stream)))
112     (cond
113       ((char= ch #\))
114        (%read-char stream)
115        nil)
116       ((char= ch #\.)
117        (%read-char stream)
118        (skip-whitespaces-and-comments stream)
119        (prog1 (ls-read stream)
120          (unless (char= (%read-char stream) #\))
121            (error "')' was expected."))))
122       (t
123        (cons (ls-read stream) (%read-list stream))))))
124
125 (defvar *eof* (make-symbol "EOF"))
126 (defun ls-read (stream)
127   (skip-whitespaces-and-comments stream)
128   (let ((ch (%peek-char stream)))
129     (cond
130       ((null ch)
131        *eof*)
132       ((char= ch #\()
133        (%read-char stream)
134        (%read-list stream))
135       ((char= ch #\')
136        (%read-char stream)
137        (list 'quote (ls-read stream)))
138       ((char= ch #\`)
139        (%read-char stream)
140        (list 'backquote (ls-read stream)))
141       ((char= ch #\")
142        (%read-char stream)
143        (prog1 (read-until stream (lambda (ch) (char= ch #\")))
144          (%read-char stream)))
145       ((char= ch #\,)
146        (%read-char stream)
147        (if (eql (%peek-char stream) #\@)
148            (progn (%read-char stream) (list 'unquote-splicing (ls-read stream)))
149            (list 'unquote (ls-read stream))))
150       ((char= ch #\#)
151        (%read-char stream)
152        (ecase (%read-char stream)
153          (#\'
154           (list 'function (ls-read stream)))
155          (#\+
156           (let ((feature (read-until stream #'terminalp)))
157             (cond
158               ((string= feature "common-lisp")
159                (ls-read stream);ignore
160                (ls-read stream))
161               ((string= feature "lispstrack")
162                (ls-read stream))
163               (t
164                (error "Unknown reader form.")))))))
165       (t
166        (let ((string (read-until stream #'terminalp)))
167          (if (every #'digit-char-p string)
168              (parse-integer string)
169              (intern (string-upcase string))))))))
170
171 (defun ls-read-from-string (string)
172   (ls-read (make-string-stream string)))
173
174
175 ;;;; Compiler
176
177 (let ((counter 0))
178   (defun make-var-binding (symbol)
179     (cons symbol (concat "v" (integer-to-string (incf counter))))))
180
181 (let ((counter 0))
182   (defun make-func-binding (symbol)
183     (cons symbol (concat "f" (integer-to-string (incf counter))))))
184
185 (defvar *compilations* nil)
186
187 (defun ls-compile-block (sexps env fenv)
188   (join-trailing (mapcar (lambda (x)
189                            (ls-compile x env fenv))
190                          sexps)
191                  ";
192 "))
193
194 (defun extend-env (args env)
195   (append (mapcar #'make-var-binding args) env))
196
197 (defparameter *env* '())
198 (defparameter *fenv* '())
199
200 (defun ls-lookup (symbol env)
201   (let ((binding (assoc symbol env)))
202     (and binding (cdr binding))))
203
204 (defun lookup-variable (symbol env)
205   (or (ls-lookup symbol env)
206       (ls-lookup symbol *env*)
207       (error "Undefined variable `~a'"  symbol)))
208
209 (defun lookup-function (symbol env)
210   (or (ls-lookup symbol env)
211       (ls-lookup symbol *fenv*)
212       (error "Undefined function `~a'"  symbol)))
213
214 (defmacro define-compilation (name args &body body)
215   ;; Creates a new primitive `name' with parameters args and
216   ;; @body. The body can access to the local environment through the
217   ;; variable ENV.
218   `(push (list ',name (lambda (env fenv ,@args) ,@body))
219          *compilations*))
220
221 (defvar *toplevel-compilations*)
222
223 (define-compilation if (condition true false)
224   (concat "("
225           (ls-compile condition env fenv)
226           " ? "
227           (ls-compile true env fenv)
228           " : "
229           (ls-compile false env fenv)
230           ")"))
231
232 ;;; Return the required args of a lambda list
233 (defun lambda-list-required-argument (lambda-list)
234   (if (or (null lambda-list) (eq (car lambda-list) '&rest))
235       nil
236       (cons (car lambda-list) (lambda-list-required-argument (cdr lambda-list)))))
237
238 (defun lambda-list-rest-argument (lambda-list)
239   (second (member '&rest lambda-list)))
240
241 (define-compilation lambda (lambda-list &rest body)
242   (let ((required-arguments (lambda-list-required-argument lambda-list))
243         (rest-argument (lambda-list-rest-argument lambda-list)))
244     (let ((new-env (extend-env (cons rest-argument required-arguments) env)))
245       (concat "(function ("
246               (join (mapcar (lambda (x) (lookup-variable x new-env))
247                             required-arguments)
248                     ",")
249               "){"
250               *newline*
251               (if rest-argument
252                   (concat "var " (lookup-variable rest-argument new-env) ";" *newline*
253                           "for (var i = arguments.length-1; i>="
254                           (integer-to-string (length required-arguments))
255                           "; i--)" *newline*
256                           (lookup-variable rest-argument new-env) " = "
257                           "{car: arguments[i], cdr: " (lookup-variable rest-argument new-env) "};"
258                           *newline*)
259                   "")
260               (concat (ls-compile-block (butlast body) new-env fenv)
261                       "return " (ls-compile (car (last body)) new-env fenv) ";")
262               *newline*
263               "})"))))
264
265 (define-compilation fsetq (var val)
266   (concat (lookup-function var fenv)
267           " = "
268           (ls-compile val env fenv)))
269
270 (define-compilation setq (var val)
271   (concat (lookup-variable var env)
272           " = "
273            (ls-compile val env fenv)))
274
275
276 ;;; Literals
277
278 (defun literal->js (sexp)
279   (cond
280     ((null sexp) "undefined")
281     ((integerp sexp) (integer-to-string sexp))
282     ((stringp sexp) (concat "\"" sexp "\""))
283     ((symbolp sexp) (concat "{name: \"" (symbol-name sexp) "\"}"))
284     ((consp sexp) (concat "{car: "
285                           (literal->js (car sexp))
286                           ", cdr: "
287                           (literal->js (cdr sexp)) "}"))))
288
289 (let ((counter 0))
290   (defun literal (form)
291     (let ((var (concat "l" (integer-to-string (incf counter)))))
292       (push (concat "var " var " = " (literal->js form)) *toplevel-compilations*)
293       var)))
294
295 (define-compilation quote (sexp)
296   (literal sexp))
297
298 (define-compilation debug (form)
299   (concat "console.log(" (ls-compile form env fenv) ")"))
300
301 (define-compilation while (pred &rest body)
302   (concat "(function(){ while("
303           (ls-compile pred env fenv)
304           "){"
305           (ls-compile-block body env fenv)
306           "}})()"))
307
308 (define-compilation function (x)
309   (cond
310     ((and (listp x) (eq (car x) 'lambda))
311      (ls-compile x env fenv))
312     ((symbolp x)
313      (lookup-function x fenv))))
314
315 #+common-lisp
316 (defmacro eval-when-compile (&body body)
317   `(eval-when (:compile-toplevel :load-toplevel :execute)
318      ,@body))
319
320 (define-compilation eval-when-compile (&rest body)
321   (eval (cons 'progn body))
322   nil)
323
324 (defmacro define-transformation (name args form)
325   `(define-compilation ,name ,args
326      (ls-compile ,form env fenv)))
327
328 (define-transformation progn (&rest body)
329   `((lambda () ,@body)))
330
331 (define-transformation let (bindings &rest body)
332   `((lambda ,(mapcar 'car bindings) ,@body)
333     ,@(mapcar 'cadr bindings)))
334
335 ;;; A little backquote implementation without optimizations of any
336 ;;; kind for lispstrack.
337 (defun backquote-expand-1 (form)
338   (cond
339     ((symbolp form)
340      (list 'quote form))
341     ((atom form)
342      form)
343     ((eq (car form) 'unquote)
344      (car form))
345     ((eq (car form) 'backquote)
346      (backquote-expand-1 (backquote-expand-1 (cadr form))))
347     (t
348      (cons 'append
349            (mapcar (lambda (s)
350                      (cond
351                        ((and (listp s) (eq (car s) 'unquote))
352                         (list 'list (cadr s)))
353                        ((and (listp s) (eq (car s) 'unquote-splicing))
354                         (cadr s))
355                        (t
356                         (list 'list (backquote-expand-1 s)))))
357                    form)))))
358
359 (defun backquote-expand (form)
360   (if (and (listp form) (eq (car form) 'backquote))
361       (backquote-expand-1 (cadr form))
362       form))
363
364 (defmacro backquote (form)
365   (backquote-expand-1 form))
366
367 (define-transformation backquote (form)
368   (backquote-expand-1 form))
369
370 ;;; Primitives
371
372 (define-compilation + (x y)
373   (concat "((" (ls-compile x env fenv) ") + (" (ls-compile y env fenv) "))"))
374
375 (define-compilation - (x y)
376   (concat "((" (ls-compile x env fenv) ") - (" (ls-compile y env fenv) "))"))
377
378 (define-compilation * (x y)
379   (concat "((" (ls-compile x env fenv) ") * (" (ls-compile y env fenv) "))"))
380
381 (define-compilation / (x y)
382   (concat "((" (ls-compile x env fenv) ") / (" (ls-compile y env fenv) "))"))
383
384 (define-compilation = (x y)
385   (concat "((" (ls-compile x env fenv) ") == (" (ls-compile y env fenv) "))"))
386
387 (define-compilation mod (x y)
388   (concat "((" (ls-compile x env fenv) ") % (" (ls-compile y env fenv) "))"))
389
390 (define-compilation floor (x)
391   (concat "(Math.floor(" (ls-compile x env fenv) "))"))
392
393 (define-compilation null (x)
394   (concat "(" (ls-compile x env fenv) "== undefined)"))
395
396 (define-compilation cons (x y)
397   (concat "{car: " (ls-compile x env fenv) ", cdr: " (ls-compile y env fenv) "}"))
398
399 (define-compilation car (x)
400   (concat "(" (ls-compile x env fenv) ").car"))
401
402 (define-compilation cdr (x)
403   (concat "(" (ls-compile x env fenv) ").cdr"))
404
405 (define-compilation make-symbol (name)
406   (concat "{name: " (ls-compile name env fenv) "}"))
407
408 (define-compilation symbol-name (x)
409   (concat "(" (ls-compile x env fenv) ").name"))
410
411 (define-compilation eq (x y)
412   (concat "(" (ls-compile x env fenv) " === " (ls-compile y env fenv) ")"))
413
414 (define-compilation string (x)
415   (concat "String.fromCharCode( " (ls-compile x env fenv) ")"))
416
417 (define-compilation char (string index)
418   (concat "("
419           (ls-compile string env fenv)
420           ").charCodeAt("
421           (ls-compile index env fenv)
422           ")"))
423
424 (define-compilation concat-two (string1 string2)
425   (concat "("
426           (ls-compile string1 env fenv)
427           ").concat("
428           (ls-compile string2 env fenv)
429           ")"))
430
431 (define-compilation funcall (func &rest args)
432   (concat "("
433           (ls-compile func env fenv)
434           ")("
435           (join (mapcar (lambda (x)
436                           (ls-compile x env fenv))
437                         args)
438                 ", ")
439           ")"))
440
441 (define-compilation new ()
442   "{}")
443
444 (define-compilation get (object key)
445   (concat "(" (ls-compile object env fenv) ")[" (ls-compile key env fenv) "]"))
446
447 (define-compilation set (object key value)
448   (concat "(("
449           (ls-compile object env fenv)
450           ")["
451           (ls-compile key env fenv) "]"
452           " = " (ls-compile value env fenv) ")"))
453
454
455 (defun %compile-defvar (name)
456   (push (make-var-binding name) *env*)
457   (push (concat "var " (lookup-variable name *env*)) *toplevel-compilations*))
458
459 (defun %compile-defun (name)
460   (push (make-func-binding name) *fenv*)
461   (push (concat "var " (lookup-variable name *fenv*)) *toplevel-compilations*))
462
463 (defun %compile-defmacro (name lambda)
464   (push (cons name (cons 'macro lambda)) *fenv*))
465
466 (defun ls-macroexpand-1 (form &optional env fenv)
467   (let ((function (cdr (assoc (car form) *fenv*))))
468     (if (and (listp function) (eq (car function) 'macro))
469         (apply (eval (cdr function)) (cdr form))
470         form)))
471
472 (defun compile-funcall (function args env fenv)
473   (cond
474     ((symbolp function)
475      (concat (lookup-function function fenv)
476              "("
477              (join (mapcar (lambda (x) (ls-compile x env fenv)) args)
478                    ", ")
479              ")"))
480     ((and (listp function) (eq (car function) 'lambda))
481      (concat "(" (ls-compile function env fenv) ")("
482              (join (mapcar (lambda (x) (ls-compile x env fenv)) args)
483                    ", ")
484              ")"))
485     (t
486      (error "Invalid function designator ~a." function))))
487
488 (defun ls-compile (sexp &optional env fenv)
489   (cond
490     ((symbolp sexp) (lookup-variable sexp env))
491     ((integerp sexp) (integer-to-string sexp))
492     ((stringp sexp) (concat "\"" sexp "\""))
493     ((listp sexp)
494      (let ((sexp (ls-macroexpand-1 sexp env fenv)))
495        (let ((compiler-func (second (assoc (car sexp) *compilations*))))
496          (if compiler-func
497              (apply compiler-func env fenv (cdr sexp))
498              (compile-funcall (car sexp) (cdr sexp) env fenv)))))))
499
500 (defun ls-compile-toplevel (sexp)
501   (setq *toplevel-compilations* nil)
502   (let ((code (ls-compile sexp)))
503     (prog1
504         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
505                               *toplevel-compilations*)
506                       "")
507                 code)
508       (setq *toplevel-compilations* nil))))
509
510 #+common-lisp
511 (progn
512   (defun ls-compile-file (filename output)
513     (with-open-file (in filename)
514       (with-open-file (out output :direction :output :if-exists :supersede)
515         (loop
516            for x = (ls-read in)
517            until (eq x *eof*)
518            for compilation = (ls-compile-toplevel x)
519            when compilation do (write-line (concat compilation "; ") out)))))
520   (defun bootstrap ()
521     (ls-compile-file "lispstrack.lisp" "lispstrack.js")))