Class: SyntaxTree::Bf::Evaluate::Compiler

Inherits:
Visitor
  • Object
show all
Defined in:
lib/syntax_tree/bf/evaluate.rb

Overview

Takes a bf syntax tree and compiles it down to a simple bytecode. The instructions almost entirely map to the tree nodes except:

  • Root - replaced by its contents

  • Loop - replaced by a jmz (jump if zero) and a jmp (unconditional jump)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Visitor

#visit, #visit_all, #visit_child_nodes

Constructor Details

#initializeCompiler

Returns a new instance of Compiler.



15
16
17
# File 'lib/syntax_tree/bf/evaluate.rb', line 15

def initialize
  @insns = []
end

Instance Attribute Details

#insnsObject (readonly)

Returns the value of attribute insns.



13
14
15
# File 'lib/syntax_tree/bf/evaluate.rb', line 13

def insns
  @insns
end

Instance Method Details

#visit_decrement(node) ⇒ Object



37
38
39
# File 'lib/syntax_tree/bf/evaluate.rb', line 37

def visit_decrement(node)
  insns << [:dec]
end

#visit_increment(node) ⇒ Object



33
34
35
# File 'lib/syntax_tree/bf/evaluate.rb', line 33

def visit_increment(node)
  insns << [:inc]
end

#visit_input(node) ⇒ Object



49
50
51
# File 'lib/syntax_tree/bf/evaluate.rb', line 49

def visit_input(node)
  insns << [:inp]
end

#visit_loop(node) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/syntax_tree/bf/evaluate.rb', line 23

def visit_loop(node)
  index = insns.length
  insns << [:jmz, -1]

  super

  insns << [:jmp, index]
  insns[index][1] = insns.length
end

#visit_output(node) ⇒ Object



53
54
55
# File 'lib/syntax_tree/bf/evaluate.rb', line 53

def visit_output(node)
  insns << [:out]
end

#visit_root(node) ⇒ Object



19
20
21
# File 'lib/syntax_tree/bf/evaluate.rb', line 19

def visit_root(node)
  super
end

#visit_shift_left(node) ⇒ Object



45
46
47
# File 'lib/syntax_tree/bf/evaluate.rb', line 45

def visit_shift_left(node)
  insns << [:shl]
end

#visit_shift_right(node) ⇒ Object



41
42
43
# File 'lib/syntax_tree/bf/evaluate.rb', line 41

def visit_shift_right(node)
  insns << [:shr]
end