As a homework on DSL, I need to write inline assembler in Ruby. I know The joke is on us: how Ruby 1.9 supports the Goto statement , but I should not use it. This is a very simple implementation when the assembler has four registers - ax , bx , cx , dx , containing integer values ββon which I can perform some operations, such as setting their values ββ( mov ), comparing two registers ( cmp ), increasing the register ( inc ), jumping to a specific location ( jmp ) and several other types. The interface will be something like this:
Asm.asm do mov cx, 1 jmp l1 mov ax, 1 label l1 mov dx, 1 end
The jmp method will accept either the label name or the serial number of one of the other functions. So my question is: in the block:
{ mov cx, 1 jmp l1 mov ax, 1 label l1 mov dx, 1 }
how can I track the current function number. My implementation looks something like this:
module Asm def self.asm(&block) memory = Memory.new memory.instance_eval(&block) memory.table.values end class Memory attr_reader :table def initialize @table = { ax: 0, bx: 0, cx: 0, dx: 0 } ... end ... def mov(destination_register, source) ... end def inc(destination_register, value = 1) ... end def dec(destination_register, value = 1) ... end ... end end
I am stuck in implementing jmp aka goto method. One of my ideas was to use a hash containing all the called methods and their arguments, or a loop loop containing instructions, and to execute or not to execute methods based on conditions stored in global variables, but I could not handle it. So, for example, is there a way to split a block and store each instruction in an array / hash, and then execute it based on its index or something similar. Any help is appreciated. Thank you so much in advance.