Skip to content

Instantly share code, notes, and snippets.

@andkerosine
Created September 9, 2012 16:15
Show Gist options
  • Save andkerosine/3685359 to your computer and use it in GitHub Desktop.
Save andkerosine/3685359 to your computer and use it in GitHub Desktop.
Whitespace assembler in Ruby
ops = %w[push pop dup copy swap slide add sub mul div mod store load label call jump jz jn ret exit ichr inum ochr onum]
quat = [5, 31, 29, 25, 30, 27, 149, 150, 151, 153, 154, 41, 42, 53, 54, 55, 57, 58, 59, 63, 185, 186, 181, 182]
ops = Hash[ops.zip quat.map { |q| q.to_s(4).tr '123', " \t\n" }]
def encode num
(num < 0 ? "\t" : ' ') + ('%b' % num.abs).tr('01', " \t") + "\n"
end
source = File.read ARGV[0]
source.gsub! /\s*[;#].+/, ''
insns = source.scan /(#{ops.keys.join '|'}|.+:) *(.+)?/
out = ''
insns.each do |insn|
op, arg = insn
op, arg = 'label', op.to_i if op[':']
out << ops[op]
out << encode(arg.to_i) if arg
end
File.open(ARGV[0].chomp('.asm') + '.ws', 'w') { |f| f << out }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment