Skip to content

Instantly share code, notes, and snippets.

@metacritical
Forked from ujihisa/bf2asm.rb
Created August 27, 2012 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metacritical/3485773 to your computer and use it in GitHub Desktop.
Save metacritical/3485773 to your computer and use it in GitHub Desktop.
brainf**k compiler for 32bit X86 Linux
puts DATA.read
labelnum = 0
labelstack = []
ARGF.each_char do |c|
puts " # #{c}"
case c
when '>'
puts ' addl $4, %eax'
when '<'
puts ' addl $-4, %eax'
when '+'
puts ' addl $1, (%eax)'
when '-'
puts ' addl $-1, (%eax)'
when '['
labelbegin, labelend = [labelnum += 1, labelnum += 1]
labelstack.push([labelbegin, labelend])
puts "L#{labelbegin}:"
puts ' cmp $0, (%eax)'
puts " jz L#{labelend}"
when ']'
labelbegin, labelend = labelstack.pop
puts " jmp L#{labelbegin}"
puts "L#{labelend}:"
when '.'
puts " pushl %eax"
puts " pushl (%eax)"
puts " call putchar"
puts " popl %eax # just to throw it away"
puts " popl %eax"
when ','
puts " pushl %eax"
puts " call getchar"
puts " movl %eax, %ecx"
puts " popl %eax"
puts " movl %ecx, (%eax)"
else
# nop
end
end
puts " movl $0, %eax"
puts " leave"
puts " ret"
__END__
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
subl $4, %esp
movl $0, (%esp)
movl %esp, %eax
$ ruby bf2asm.rb ./helloworld.bf > hello.s
$ as --32 hello.s -o a.o && ld -m elf_i386 -dynamic-linker /lib32/ld-linux.so.2 /usr/lib32/crt1.o /usr/lib32/crti.o -lc /usr/lib32/crtn.o a.o -o ./a && ./a
Hello World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment