Class: Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/rampi/compiler.rb

Instance Method Summary collapse

Instance Method Details

#compile(ramp:, code:) ⇒ Object



2
3
4
5
6
7
8
9
# File 'lib/rampi/compiler.rb', line 2

def compile(ramp:, code:)
  code_body = code.map { |num, code_line|
    code_line.map { |v| v && try(v) }.reject(&:nil?).join(' ')
  }.join(', ')

  "r #{ramp};\n" \
  "#{ code_body.empty? ? '' : "c #{code_body};\n"}"
end

#try(node_or_value) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/rampi/compiler.rb', line 31

def try(node_or_value)
  if node_or_value.respond_to?(:accept)
    node_or_value.accept(self)
  else
    node_or_value
  end
end

#visit_binary_expr(n) ⇒ Object



27
28
29
# File 'lib/rampi/compiler.rb', line 27

def visit_binary_expr(n)
  "(#{try(n.left)}#{n.op}#{try(n.right)})"
end

#visit_func(n) ⇒ Object



11
12
13
# File 'lib/rampi/compiler.rb', line 11

def visit_func(n)
  "#{n.name}(#{n.args.map { |arg| try(arg) }.join('\,')})"
end

#visit_unary_expr(n) ⇒ Object



23
24
25
# File 'lib/rampi/compiler.rb', line 23

def visit_unary_expr(n)
  "#{n.op}#{try(n.value)}"
end

#visit_var(n) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/rampi/compiler.rb', line 15

def visit_var(n)
  case n.name
    when :v1 then "$v1"
    when :v2 then "$v2"
    else n.name.to_s
  end
end