Last active
August 29, 2015 14:00
某教科書のアセンブリコードの解釈器.バグあったら教えてね.クッソ適当につくったので美しさなんて考慮してません.ライセンスは,GPLv3です.
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
# Assembly Interpret | |
# @author Shusui MOYATANI | |
# @license GNU General Public License version 3 | |
$memory = [] | |
$calreg = 0 | |
# パースして$memoryに保存 | |
def parse_store(str) | |
tmp = str.split(/\s+/) | |
if tmp.length == 3 | |
$memory[tmp[0].to_i] = { | |
:operator => tmp[1], | |
:operand => tmp[2].to_f == tmp[2].to_i ? tmp[2].to_i : tmp[2].to_f | |
} | |
elsif tmp.length == 2 | |
$memory[tmp[0].to_i] = { | |
:operator => tmp[1], | |
:operand => tmp[1].to_f == tmp[1].to_i ? tmp[1].to_i : tmp[1].to_f | |
} | |
else | |
raise "InputFileError" | |
end | |
puts "!!! #{tmp}" if $DEBUG | |
end | |
# wordを読み込んで実行する | |
def exec(word) | |
case word[:operator] | |
when "add" | |
puts "! $calreg = $calreg(#{$calreg}) + $memory[#{word[:operand]}] (#{$memory[word[:operand]][:operand]})" if $DEBUG | |
$calreg += $memory[word[:operand]][:operand] | |
when "subtract" | |
puts "! $calreg = $calreg(#{$calreg}) - $memory[#{word[:operand]}] (#{$memory[word[:operand]][:operand]})" if $DEBUG | |
$calreg -= $memory[word[:operand]][:operand] | |
when "multiply" | |
puts "! $calreg = $calreg(#{$calreg}) * $memory[#{word[:operand]}] (#{$memory[word[:operand]][:operand]})" if $DEBUG | |
$calreg *= $memory[word[:operand]][:operand] | |
when "divide" | |
puts "! $calreg = $calreg(#{$calreg}) / $memory[#{word[:operand]}] (#{$memory[word[:operand]][:operand]})" if $DEBUG | |
$calreg /= $memory[word[:operand]][:operand] | |
when "store" | |
$memory[word[:operand]][:operand] = $calreg | |
puts "! $memory[#{word[:operand]}] = #{$calreg}" if $DEBUG | |
when "load" | |
$calreg = $memory[word[:operand]][:operand] | |
puts "! calreg = $memory[#{word[:operand]}] (#{$memory[word[:operand]][:operand]})" if $DEBUG | |
when "jump" | |
$i = word[:operand] - 1 | |
when "jumpzero" | |
if $calreg == 0 | |
puts "! jump #{word[:operand]}" | |
$i = word[:operand] - 1 | |
end | |
when "print" | |
puts "#{$calreg}" | |
when "halt" | |
exit | |
else | |
raise "UndefinedInstructionError" | |
end | |
end | |
### main | |
if ARGV[0] == nil | |
puts "specify input file" | |
exit 1 | |
end | |
File.open(ARGV[0], "r").each_line do |line| | |
parse_store line | |
end | |
$i = 0 | |
while true | |
puts "! trace #{$i}: #{$memory[$i].each_value.to_a * " "}" if $DEBUG | |
exec $memory[$i] | |
$i += 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment