Created
November 30, 2008 03:17
-
-
Save kragen/30376 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby assembler DSEL, following tqbf’s unreleased one: | |
# http://news.ycombinator.com/item?id=378457 | |
$assembly_output = nil | |
class Program | |
def initialize() @contents = [] end | |
def add() $assembly_output = self; yield end | |
def append(something) @contents.push(something) end | |
end | |
class Assembler | |
def initialize() | |
@prog = Program.new | |
end | |
def instruction(opcode, *args) $assembly_output.append([opcode, args]) end | |
def push(arg) instruction("push", arg) end | |
def mov(a, b) instruction("mov", a, b) end | |
def pop(arg) instruction("pop", arg) end | |
def xor(a, b) instruction("xor", a, b) end | |
def ret() instruction("ret") end | |
def ebx() 'ebx' end | |
def eax() 'eax' end | |
def method_missing(id, *args) "some label called #{id}" end | |
def doit | |
@epilog ||= @prog.add { | |
push ebx | |
mov ebx, retv | |
mov [ebx], eax | |
pop ebx | |
xor eax, eax | |
ret | |
} | |
end | |
end | |
# irb(main):002:0> Assembler.new.doit | |
# => [["push", ["ebx"]], ["mov", ["ebx", "some label called retv"]], | |
# ["mov", [["ebx"], "eax"]], ["pop", ["ebx"]], ["xor", ["eax", "eax"]], | |
# ["ret", []]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment