Class: SyntaxTree::Bf::Evaluate::Machine
- Inherits:
-
Object
- Object
- SyntaxTree::Bf::Evaluate::Machine
- 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
-
#insns ⇒ Object
readonly
Returns the value of attribute insns.
-
#stdin ⇒ Object
readonly
Returns the value of attribute stdin.
-
#stdout ⇒ Object
readonly
Returns the value of attribute stdout.
Instance Method Summary collapse
-
#initialize(insns, stdin: STDIN, stdout: STDOUT) ⇒ Machine
constructor
A new instance of Machine.
- #run ⇒ Object
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
#insns ⇒ Object (readonly)
Returns the value of attribute insns.
62 63 64 |
# File 'lib/syntax_tree/bf/evaluate.rb', line 62 def insns @insns end |
#stdin ⇒ Object (readonly)
Returns the value of attribute stdin.
62 63 64 |
# File 'lib/syntax_tree/bf/evaluate.rb', line 62 def stdin @stdin end |
#stdout ⇒ Object (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
#run ⇒ Object
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 |