-
Notifications
You must be signed in to change notification settings - Fork 0
/
mrcl_asm.rb
66 lines (53 loc) · 1.13 KB
/
mrcl_asm.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require "pp"
require "json"
def parse(src)
alines = []
src.each_line do |line|
words = line.sub(/#.*/, "").strip.split(/ +/)
unless words.empty?
alines << words
end
end
alines
end
def create_label_addr_map(alines)
map = {}
alines.each_with_index do |aline, addr|
head, *rest = aline
case head
when "label"
name = rest[0]
map[name] = addr
end
end
map
end
def to_machine_code_operand(arg)
case arg
when /^\[(.+)\]$/ then "mem:#{$1}"
when /^-?\d+$/ then arg.to_i
else arg
end
end
src = File.read(ARGV[0])
alines = parse(src)
# key: ラベル名、 value: アドレス のマッピングを作る
label_addr_map = create_label_addr_map(alines)
alines.each do |aline|
head, *rest = aline
insn = [head]
case head
when "label"
insn << rest[0]
when "jmp", "je", "call"
label_name = rest[0]
if label_addr_map.key?(label_name)
insn << label_addr_map[label_name]
else
raise "label not found (#{label_name})"
end
else
insn += rest.map { |arg| to_machine_code_operand(arg) }
end
puts JSON.generate(insn)
end