Class: SyntaxTree::Bf::Evaluate::Machine

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

Overview

This is the virtual machine that runs the set of instructions that the compiler outputs. Its state is kept on an infinite tape of memory, which is paired with a cursor.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(insns, stdin: STDIN, stdout: STDOUT) ⇒ Machine

Returns a new instance of Machine.



64
65
66
67
68
# File 'lib/syntax_tree/bf/evaluate.rb', line 64

def initialize(insns, stdin: STDIN, stdout: STDOUT)
  @insns = insns
  @stdin = stdin
  @stdout = stdout
end

Instance Attribute Details

#insnsObject (readonly)

Returns the value of attribute insns.



62
63
64
# File 'lib/syntax_tree/bf/evaluate.rb', line 62

def insns
  @insns
end

#stdinObject (readonly)

Returns the value of attribute stdin.



62
63
64
# File 'lib/syntax_tree/bf/evaluate.rb', line 62

def stdin
  @stdin
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



62
63
64
# File 'lib/syntax_tree/bf/evaluate.rb', line 62

def stdout
  @stdout
end

Instance Method Details

#runObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/syntax_tree/bf/evaluate.rb', line 70

def run
  pc = 0

  tape = Hash.new { 0 }
  cursor = 0

  while pc < insns.length
    insn = insns[pc]
    pc += 1

    case insn
    in [:inc]
      tape[cursor] += 1
    in [:dec]
      tape[cursor] -= 1
    in [:shr]
      cursor += 1
    in [:shl]
      cursor -= 1
    in [:inp]
      tape[cursor] = stdin.getc.ord
    in [:out]
      stdout.putc(tape[cursor].chr)
    in [:jmz, offset]
      pc = offset if tape[cursor] == 0
    in [:jmp, offset]
      pc = offset
    end
  end

  tape
end