Permalink
Browse files

implicit conversions for console.log and +

  • Loading branch information...
ujihisa committed Jan 2, 2013
1 parent 30ad8c8 commit f28e7f55559f4919d6718539d413f0e65bd4a9e0
Showing with 36 additions and 13 deletions.
  1. +36 −13 runtime.clj
View
@@ -12,33 +12,56 @@
'acc))]]))]])
[]))])
(defn js-boolean
"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean"
[value]
(not (get #{0 'null false 'NaN 'undefined} value false)))
(defn js-number
"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number"
[value]
(condp instance? value
String (if (empty? value)
0
(let [x (read-string value)]
(if (number? x) x 'NaN)))
Long value
'NaN))
(defn js-string
"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String"
[value]
(.toString value))
(defn evaluate [expr env]
"assumption: env won't change"
(if (list? expr)
(let [[car & cdr] expr]
(condp = car
'fcall (let [func (evaluate (first cdr) env)
(case car
fcall (let [func (evaluate (first cdr) env)
args (map #(evaluate % env) (second cdr))]
(condp = func
'console.log (println (first args))
'+ (+ (first args) (second args))
(case func
console.log (println (js-string (first args)))
+ (if (every? number? args)
(+ (first args) (second args))
(str (js-string (first args)) (js-string (second args))))
(prn 'must-not-happen 'missing-function func)))
'quote (get env (first cdr))
quote (get env (first cdr))
expr))
expr))
(defn run [stmts]
(loop [[stmt & stmts] stmts env {'console.log 'console.log '+ '+}]
(loop [[stmt & stmts] stmts env {'console.log 'console.log '+ '+ 'null 'null 'undefined 'undefined 'NaN 'NaN}]
(when stmt
(let [[car & cdr] stmt]
(condp = car
'var (let [vname (first cdr)
vvalue (evaluate (second cdr) env)]
(recur stmts (assoc env vname vvalue)))
'return (prn 'not-implemented-yet)
(case car
var (let [vname (first cdr)
vvalue (evaluate (second cdr) env)]
(recur stmts (assoc env vname vvalue)))
return (prn 'not-implemented-yet)
(do
(evaluate stmt env)
(recur stmts env)))))))
(run '[(var x 1)
(fcall 'console.log [(fcall '+ ['x 2])])])
(fcall 'console.log [(fcall '+ ['x "hello"])])])

0 comments on commit f28e7f5

Please sign in to comment.