Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/ruby -Ku
- require 'bindata'
- class Brainfuck
- def self.read_file file
- if not File.exist? file
- puts "File " + file + " doesn't exist!"
- exit 1
- end
- @new_name = file.gsub(/.bf/,'')
- @@code = File.open(file).readlines.map { |line| line.chomp }.join.split('')
- end
- def self.validate
- @a = 0
- @@code.each do |item|
- if item == '['
- @a += 1
- end
- if item == ']'
- @a -= 1
- end
- end
- if @a > 0
- puts "Unexpected [ or ]"
- exit 1
- end
- end
- def self.compile
- $cells = Array.new
- $cell = 0
- @fun = Proc.new do |command,file|
- if $cells[$cell].nil?
- $cells[$cell] = 0
- end
- case command
- when '+'
- BinData::Int8be.new(0x1).write(file)
- $cells[$cell] += 1
- when '-'
- BinData::Int8be.new(0x2).write(file)
- $cells[$cell] -= 1
- when '>'
- BinData::Int8be.new(0x3).write(file)
- $cell += 1
- when '<'
- BinData::Int8be.new(0x4).write(file)
- $cell -= 1
- when ','
- BinData::Int8be.new(0x5).write(file)
- when '.'
- BinData::Int8be.new(0x6).write(file)
- end
- end
- brackets = 0
- loop_code = Array.new
- File.open(@new_name,'wb') do |file|
- @@code.each_with_index do |item,index|
- if $cells[$cell].nil?
- $cells[$cell] = 0
- end
- if item == '['
- brackets += 1
- next
- end
- if brackets > 0 and item != ']'
- loop_code << item
- next
- end
- if item == ']'
- brackets -= 1
- while $cells[$cell] != 0
- loop_code.each do |c|
- @fun.call c,file
- break if $cells[$cell] == 0
- end
- end
- next
- end
- @fun.call item,file
- end
- end
- end
- end
- ARGV.each do |file_name|
- if not File.exist? file_name
- puts "File #{file_name} doesn't exist!"
- exit 1
- end
- Brainfuck.read_file file_name
- Brainfuck.validate
- Brainfuck.compile
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement