forked from proglangclass/interpreter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs_generator.rb
More file actions
54 lines (45 loc) · 869 Bytes
/
js_generator.rb
File metadata and controls
54 lines (45 loc) · 869 Bytes
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
class JsGenerator
def initialize
@code = []
@locals = []
end
# Emit the Javascript code
def emit(code)
@code << code
end
# true if the local variable as been defined
def has_local?(name)
@locals.include?(name)
end
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
def set_local(name, value)
@locals << name unless has_local?(name)
emit "#{name} = "
value.compile(self)
end
def get_local(name)
emit name
end
def if(condition, body)
emit "if ("
condition.compile(self)
emit ") {\n"
body.compile(self)
emit "}"
end
def assemble
"var " + @locals.join(", ") + ";\n" +
@code.join
end
end