Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Last active August 29, 2015 14:00
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 syusui-s/11139253 to your computer and use it in GitHub Desktop.
Save syusui-s/11139253 to your computer and use it in GitHub Desktop.
某教科書のアセンブリコードの解釈器.バグあったら教えてね.クッソ適当につくったので美しさなんて考慮してません.ライセンスは,GPLv3です.
# 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