From: Lyndon Samson Date: 2005-10-24T13:29:37+09:00 Subject: Bit of fun II More idle coding :-) A simple Compiler/Assembler/VM for a ( very basic ) RPN (dc) style language. I suspect its quite amenable to golfing, but at a cost to readability. def compile(pgm) outs = [] lines = pgm.split("\n") lines.each { |line| tokens = line.strip.chomp.split(" ") pos = 0 while true case tokens[pos] when '+' outs << "pop 1" outs << "pop 2" outs << "addr 1,2" outs << "push 1" when 'p' outs << "pop 1" outs << "print 1" when '',nil else outs << "loadr 1,#{tokens[pos]}" outs << "push 1" end pos = pos + 1 break if pos > tokens.length end } return outs.join("\n") end def assemble(pgm) mem = [] pc = 0 lines = pgm.split("\n") lines.each { |line| tokens = line.strip.split(/ |,/) case tokens[0] when 'loadr' mem[pc]=1 mem[pc+1]=tokens[1].to_i mem[pc+2]=tokens[2].to_i pc = pc+3 when 'addr' mem[pc]=2 mem[pc+1]=tokens[1].to_i mem[pc+2]=tokens[2].to_i pc = pc+3 when 'print' mem[pc]=3 mem[pc+1]=tokens[1].to_i pc = pc+2 when 'push' mem[pc]=4 mem[pc+1]=tokens[1].to_i pc = pc+2 when 'pop' mem[pc]=5 mem[pc+1]=tokens[1].to_i pc = pc+2 end } mem.push(0) return mem end def execute(mem) pc = 0 regs=[] stack=[] while true #puts "> PC:#{pc} CODE:#{mem[pc]} STACK:#{stack.join(',')}" case mem[pc] when 0 break when 1 regs[mem[pc+1]] = mem[pc+2] pc=pc+3 when 2 regs[mem[pc+1]] = regs[mem[pc+1]] + regs[mem[pc+2]] pc=pc+3 when 3 puts "#{regs[mem[pc+1]]}" pc=pc+2 when 4 #push stack.push(regs[mem[pc+1]]) pc=pc+2 when 5 #pop regs[mem[pc+1]] = stack.pop() pc=pc+2 end end end aapgm = compile("12 10 + 14 + p") code = assemble(aapgm) execute(code) -- Into RFID? www.rfidnewsupdate.com Simple, fast, news.