Class: Kaguya::Compiler

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

Instance Method Summary collapse

Constructor Details

#initialize(ast) ⇒ Compiler

Returns a new instance of Compiler.

Parameters:



6
7
8
# File 'lib/kaguya/compiler.rb', line 6

def initialize(ast)
  @ast = ast
end

Instance Method Details

#compileArray

Returns:

  • (Array)


11
12
13
14
15
# File 'lib/kaguya/compiler.rb', line 11

def compile
  iseq = @ast.accept(self)
  iseq << [:leave, nil]
  iseq
end

#visit(node) ⇒ Array

Parameters:

Returns:

  • (Array)


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
# File 'lib/kaguya/compiler.rb', line 19

def visit(node)
  iseq = []

  case node.type
  when :forward
    iseq << [:forward, nil]
  when :backward
    iseq << [:backward, nil]
  when :increment
    iseq << [:increment, nil]
  when :decrement
    iseq << [:decrement, nil]
  when :output
    iseq << [:output, nil]
  when :input
    iseq << [:input, nil]
  when :while
    sub_iseq = []

    node.children.each do |child|
      sub_iseq.concat(child.accept(self))
    end

    iseq << [:branch_ifzero, sub_iseq.size + 2]
    iseq.concat(sub_iseq)
    iseq << [:branch_unlesszero, -sub_iseq.size]
  when :root
    node.children.each do |child|
      iseq.concat(child.accept(self))
    end
  else
    raise 'Invalid node!'
  end

  iseq
end