Rewrite *newline* without literal string
[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 :execute)
318      ,@body))
319
320 (defvar *eval-when-compilations*)
321 (define-compilation eval-when-compile (&rest body)
322   (eval (cons 'progn body))
323   nil)
324
325 (defmacro define-transformation (name args form)
326   `(define-compilation ,name ,args
327      (ls-compile ,form env fenv)))
328
329 (define-transformation progn (&rest body)
330   `((lambda () ,@body)))
331
332 (define-transformation let (bindings &rest body)
333   `((lambda ,(mapcar 'car bindings) ,@body)
334     ,@(mapcar 'cadr bindings)))
335
336 ;;; A little backquote implementation without optimizations of any
337 ;;; kind for lispstrack.
338 (defun backquote-expand-1 (form)
339   (cond
340     ((symbolp form)
341      (list 'quote form))
342     ((atom form)
343      form)
344     ((eq (car form) 'unquote)
345      (car form))
346     ((eq (car form) 'backquote)
347      (backquote-expand-1 (backquote-expand-1 (cadr form))))
348     (t
349      (cons 'append
350            (mapcar (lambda (s)
351                      (cond
352                        ((and (listp s) (eq (car s) 'unquote))
353                         (list 'list (cadr s)))
354                        ((and (listp s) (eq (car s) 'unquote-splicing))
355                         (cadr s))
356                        (t
357                         (list 'list (backquote-expand-1 s)))))
358                    form)))))
359
360 (defun backquote-expand (form)
361   (if (and (listp form) (eq (car form) 'backquote))
362       (backquote-expand-1 (cadr form))
363       form))
364
365 (defmacro backquote (form)
366   (backquote-expand-1 form))
367
368 (define-transformation backquote (form)
369   (backquote-expand-1 form))
370
371 ;;; Primitives
372
373 (define-compilation + (x y)
374   (concat "((" (ls-compile x env fenv) ") + (" (ls-compile y env fenv) "))"))
375
376 (define-compilation - (x y)
377   (concat "((" (ls-compile x env fenv) ") - (" (ls-compile y env fenv) "))"))
378
379 (define-compilation * (x y)
380   (concat "((" (ls-compile x env fenv) ") * (" (ls-compile y env fenv) "))"))
381
382 (define-compilation / (x y)
383   (concat "((" (ls-compile x env fenv) ") / (" (ls-compile y env fenv) "))"))
384
385 (define-compilation = (x y)
386   (concat "((" (ls-compile x env fenv) ") == (" (ls-compile y env fenv) "))"))
387
388 (define-compilation null (x)
389   (concat "(" (ls-compile x env fenv) "== undefined)"))
390
391 (define-compilation cons (x y)
392   (concat "{car: " (ls-compile x env fenv) ", cdr: " (ls-compile y env fenv) "}"))
393
394 (define-compilation car (x)
395   (concat "(" (ls-compile x env fenv) ").car"))
396
397 (define-compilation cdr (x)
398   (concat "(" (ls-compile x env fenv) ").cdr"))
399
400 (define-compilation make-symbol (name)
401   (concat "{name: " (ls-compile name env fenv) "}"))
402
403 (define-compilation symbol-name (x)
404   (concat "(" (ls-compile x env fenv) ").name"))
405
406 (define-compilation eq (x y)
407   (concat "(" (ls-compile x env fenv) " === " (ls-compile y env fenv) ")"))
408
409 (define-compilation code-char (x)
410   (concat "String.fromCharCode( " (ls-compile x env fenv) ")"))
411
412 (define-compilation char (string index)
413   (concat "("
414           (ls-compile string env fenv)
415           ").charCodeAt("
416           (ls-compile index env fenv)
417           ")"))
418
419 (define-compilation concat-two (string1 string2)
420   (concat "("
421           (ls-compile string1 env fenv)
422           ").concat("
423           (ls-compile string2 env fenv)
424           ")"))
425
426 (define-compilation funcall (func &rest args)
427   (concat "("
428           (ls-compile func env fenv)
429           ")("
430           (join (mapcar (lambda (x)
431                           (ls-compile x env fenv))
432                         args)
433                 ", ")
434           ")"))
435
436 (define-compilation new ()
437   "{}")
438
439 (define-compilation get (object key)
440   (concat "(" (ls-compile object env fenv) ")[" (ls-compile key env fenv) "]"))
441
442 (define-compilation set (object key value)
443   (concat "(("
444           (ls-compile object env fenv)
445           ")["
446           (ls-compile key env fenv) "]"
447           " = " (ls-compile value env fenv) ")"))
448
449
450 (defun %compile-defvar (name)
451   (push (make-var-binding name) *env*)
452   (push (concat "var " (lookup-variable name *env*)) *toplevel-compilations*))
453
454 (defun %compile-defun (name)
455   (push (make-func-binding name) *fenv*)
456   (push (concat "var " (lookup-variable name *fenv*)) *toplevel-compilations*))
457
458 (defun %compile-defmacro (name lambda)
459   (push (cons name (cons 'macro lambda)) *fenv*))
460
461 (defun ls-macroexpand-1 (form &optional env fenv)
462   (let ((function (cdr (assoc (car form) *fenv*))))
463     (if (and (listp function) (eq (car function) 'macro))
464         (apply (eval (cdr function)) (cdr form))
465         form)))
466
467 (defun compile-funcall (function args env fenv)
468   (cond
469     ((symbolp function)
470      (concat (lookup-function function fenv)
471              "("
472              (join (mapcar (lambda (x) (ls-compile x env fenv)) args)
473                    ", ")
474              ")"))
475     ((and (listp function) (eq (car function) 'lambda))
476      (concat "(" (ls-compile function env fenv) ")("
477              (join (mapcar (lambda (x) (ls-compile x env fenv)) args)
478                    ", ")
479              ")"))
480     (t
481      (error "Invalid function designator ~a." function))))
482
483 (defun ls-compile (sexp &optional env fenv)
484   (cond
485     ((symbolp sexp) (lookup-variable sexp env))
486     ((integerp sexp) (integer-to-string sexp))
487     ((stringp sexp) (concat "\"" sexp "\""))
488     ((listp sexp)
489      (let ((sexp (ls-macroexpand-1 sexp env fenv)))
490        (let ((compiler-func (second (assoc (car sexp) *compilations*))))
491          (if compiler-func
492              (apply compiler-func env fenv (cdr sexp))
493              (compile-funcall (car sexp) (cdr sexp) env fenv)))))))
494
495 (defun ls-compile-toplevel (sexp)
496   (setq *toplevel-compilations* nil)
497   (let ((code (ls-compile sexp)))
498     (prog1
499         (concat (join (mapcar (lambda (x) (concat x ";" *newline*))
500                               *toplevel-compilations*)
501                       "")
502                 code)
503       (setq *toplevel-compilations* nil))))
504
505 #+common-lisp
506 (progn
507   (defun ls-compile-file (filename output)
508     (with-open-file (in filename)
509       (with-open-file (out output :direction :output :if-exists :supersede)
510         (loop
511            for x = (ls-read in)
512            until (eq x *eof*)
513            for compilation = (ls-compile-toplevel x)
514            when compilation do (write-line (concat compilation "; ") out)))))
515   (defun bootstrap ()
516     (ls-compile-file "lispstrack.lisp" "lispstrack.js")))