-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathjs_generator.rb
64 lines (53 loc) · 1.04 KB
/
js_generator.rb
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
class JsGenerator
def initialize
@code = []
@locals = []
end
# 1;
# function() { ... };
def compile_all(nodes)
nodes.each do |node|
node.compile(self)
emit ";\n"
end
end
def number_literal(value)
emit value
end
def string_literal(value)
emit '"' + value + '"'
end
# In Javascript:
# var a, b;
# a = 1;
def set_local(name, value_node)
@locals << name unless @locals.include?(name)
emit "#{name} = "
value_node.compile(self)
end
def get_local(name)
emit name
end
# if (condition) {
# body
# }
def if(condition_node, body_node, else_body_node)
emit 'if ('
condition_node.compile(self)
emit ") {\n"
body_node.compile(self)
emit "}"
end
# Emit a chunk of Javascript code.
def emit(code)
@code << code
end
# Called at the end of compilation to assemble all the code generated.
def assemble
out = ""
if @locals.size > 0
out << "var " + @locals.join(', ') + ";\n"
end
out + @code.join
end
end