-
Notifications
You must be signed in to change notification settings - Fork 0
/
js.scm
70 lines (61 loc) · 2.06 KB
/
js.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
;; function call
;; (func -> a b c) // -> func (a, b, c);
;;
;; (a = b) -> a = b
;; (a * b + c) -> a * b + c
;; (this .. state = {}) -> this.state = {}
;; for (var i in obj) { func (obj[i]); a ++; }
;; (for (var i in obj) (func -> obj <> i) // (a ++) //)
(define-module js
(export js js-sym js-let-syms))
(select-module js)
(use util.match)
(define (join delim lst)
(if (null? lst)
""
(if (null? (cdr lst))
(car lst)
#`",(car lst),delim,(join delim (cdr lst))")))
(define (js code)
(match code
('var "var ")
('new "new ")
('in " in ")
('return "return ")
('// ";")
('.. ".")
((? symbol? sym) (symbol->string sym))
((? number? num) (number->string num))
((? string? str) #`"\",str\"")
(`(,func -> ,args ...)
#`",(js func)(,(join \",\" (map js args)))")
((() x ...)
(js `(|(| ,x |)|)))
(`(<> ,x ...)
#`"[,(js x)]")
(`(^^ ,pairs ...)
(string-append "{"
(join "," (map (lambda (p)
(js `(,(car p) |:| ,(cadr p)))
) pairs)) "}"))
(`(if (,condition ...) ,body ...)
#`"if,(js `((() ,condition) |{| ,body |}|))")
(`(else ,body ...)
#`"else,(js `(|{| ,body |}|))")
(`(for (,stmt ...) ,body ...)
#`"for,(js `((() ,stmt) |{| ,body |}|))")
(`(while (,expr ...) ,body ...)
#`"while,(js `((() ,expr) |{| ,body |}|))")
(`(function ,(? symbol? name) (,args ...) ,body ...)
#`"function ,name(,(join \",\" args)){,(js body)}")
(`(function (,args ...) ,body ...)
#`"function(,(join \",\" args)){,(js body)}")
((terms ...)
(apply string-append (map js terms)))
))
(define (js-sym) (string->symbol (string-append "$" (symbol->string (gensym)))))
(define-syntax js-let-syms
(syntax-rules ()
((_ (vars ...) body ...)
(let ((vars (js-sym)) ...)
body ...))))