Debian Codegraph @

contrib/toacme/masm2acme.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 import sys
3
4 def line_preprocess(line):
5 "split line into comment, strings and everything else"
6 result = []
7 part = ""
8 comment = None
9 quotes = None
10 for char in line:
11 # are we inside comment?
12 if comment:
13 comment += char
14 continue
15 # are we inside quotes?
16 if quotes:
17 part += char
18 if char == quotes:
19 # end of quotes
20 # if previous part was also quoted, we have to combine them,
21 # because "a""b" really means a"b
22 if result and result[-1][-1] == quotes:
23 part = result[-1][:-1] + "\\" + part
24 result.pop()
25 # use singlequotes for 1-char strings
26 if len(part) == 3:
27 part = "'" + part[1] + "'"
28 # escape backslash, singlequote, doublequote
29 if part == "'\\'":
30 part = "'\\\\'"
31 elif part == "'''":
32 part = "'\\''"
33 elif part == '"\\""':
34 part = "'\"'"
35 result.append(part) # move quoted string to result list
36 part = ""
37 quotes = None
38 continue
39 # not in quotes
40 if char == '"' or char == "'":
41 # new quotes, so finish old part
42 if part and part != ' ':
43 result.append(part)
44 # ...and start new one
45 part = char
46 quotes = char
47 continue
48 # comment?
49 if char == ';':
50 # finish old part
51 if part and part != ' ':
52 result.append(part)
53 part = ""
54 # ...and start comment
55 comment = char
56 continue
57 ## tab-to-space:
58 #if char == '\t':
59 # char = ' '
60 # skip blanks after blank
61 if part.endswith(' ') and char == ' ':
62 pass
63 else:
64 # all other characters:
65 part += char
66 # quotes still open at end of line?
67 if quotes:
68 raise Exception("Unterminated string constant in input data")
69 # append last part
70 if part:
71 result.append(part)
72 return result, comment
73
74 def single_out(items, substring):
75 "split any item containing substring into first part, substring, second part. empty parts are dropped."
76 result = []
77 for i in items:
78 while substring in i:
79 parts = i.partition(substring)
80 if parts[0]:
81 result.append(parts[0])
82 result.append(substring)
83 i = parts[2]
84 if i:
85 result.append(i)
86 return result
87
88 def unquoted_tokenize(part):
89 "split part into tokens (so do not pass string literals!)"
90 # split at spaces (and throw away all spaces)
91 items = part.split()
92 # split at commas, braces, ...
93 items = single_out(items, ',')
94 items = single_out(items, '/')
95 items = single_out(items, '=')
96 items = single_out(items, '+')
97 items = single_out(items, '-')
98 items = single_out(items, '*')
99 return items
100
101 opcodes_to_keep = [
102 # std 6502:
103 "brk", "rti", "rts", "nop",
104 "php", "plp", "pha", "pla",
105 "bpl", "bmi", "bvc", "bvs", "bcc", "bcs", "bne", "beq",
106 "clc", "sec", "cli", "sei", "clv", "cld", "sed",
107 "dex", "dey", "inx", "iny",
108 "tax", "tay", "txa", "tya", "tsx", "txs",
109 # new in 65c02:
110 "phx", "plx", "phy", "ply", "bra" # inc, dec
111 ]
112
113 opcodes_with_arg = [
114 # std 6502:
115 "ora", "and", "eor", "adc", "sta", "lda", "cmp", "sbc",
116 "asl", "rol", "lsr", "ror", "dec", "inc",
117 "ldx", "stx", "cpx", "ldy", "sty", "cpy",
118 "jsr", "jmp", "bit",
119 # new in 65c02:
120 "tsb", "trb", "stz"
121 ]
122
123 token_substitutions = {
124 ".": "*", # program counter
125 ":not:": "not", # operator
126 ":eor:": "xor", # operator
127 ":msb:": ">", # operator?
128 }
129
130 opcodes_to_replace = {
131 "org": "*=",
132 "cpu": ";!cpu", # TODO: support properly!
133 "=": "!tx",
134 "$": "!wo", # actually & instead of $, but substitution was done earlier
135 "end": "!eof",
136 "assert": "+assert",
137 "lnk": ";!source", # TODO: support properly!
138 "asla": "\tasl",
139 "lsra": "\tlsr",
140 "rola": "\trol",
141 "rora": "\tror",
142 "dea": "\tdec", # 65c02
143 "ina": "\tinc", # 65c02
144 }
145
146 opcodes_to_rename = {
147 "clr": "stz" # 65c02
148 }
149
150 def convert_opcodes(parts):
151 "convert mnemonics and pseudo opcodes"
152 if not parts:
153 return parts
154 op = parts[0]
155 parts = parts[1:]
156 if op in opcodes_to_keep:
157 return ["\t" + op] + parts
158 if op in opcodes_to_replace:
159 return [opcodes_to_replace[op]] + parts
160 # wtf?!
161 if op == "jmi":
162 op = "jmpi"
163 elif op == "jmix":
164 op = "jmpxi"
165 # convert addressing modes
166 if len(op) > 3:
167 oldop = op
168 am = op[3:]
169 op = op[:3]
170 if am == "im":
171 if parts[0] == '/':
172 parts[0] = "#>"
173 elif parts[0][0] >= 'a' and parts[0][0] <= 'z':
174 parts[0] = "#< " + parts[0]
175 else:
176 parts[0] = "#" + parts[0]
177 elif am == "ax" or am == "zx":
178 parts[-1] = parts[-1] + ", x"
179 elif am == "ay" or am == "zy":
180 parts[-1] = parts[-1] + ", y"
181 elif am == "xi":
182 parts[0] = "(" + parts[0]
183 parts[-1] = parts[-1] + ", x)"
184 elif am == "iy":
185 parts[0] = "(" + parts[0]
186 parts[-1] = parts[-1] + "), y"
187 elif am == "i":
188 parts[0] = "(" + parts[0]
189 parts[-1] = parts[-1] + ")"
190 else:
191 op = oldop
192 # convert
193 if op in opcodes_to_rename:
194 op = opcodes_to_rename[op]
195 if op in opcodes_with_arg:
196 return ["\t" + op] + parts
197 return [op] + parts
198
199 def process_code(parts):
200 "split code parts at special characters"
201 prefix = ""
202 # remember if line starts with space
203 indented = (parts[0][0] == " ")
204 # because now spaces are dropped
205 result = []
206 for part in parts:
207 # do not process quoted strings any further
208 if part.startswith("'") or part.startswith('"'):
209 result.append(part)
210 continue
211 # convert to lower case
212 part = part.lower()
213 # substitute: & becomes $
214 part = "$".join(part.split("&"))
215 # all other parts are split up into tokens
216 result.extend(unquoted_tokenize(part))
217 # convert some tokens (string literals are not in danger, as they include quotes)
218 parts = result
219 result = []
220 for part in parts:
221 if part in token_substitutions:
222 part = token_substitutions[part]
223 result.append(part)
224 # now convert
225 label = ""
226 if indented:
227 # code
228 result = convert_opcodes(result)
229 else:
230 # label or symbol definition
231 if len(result) > 1 and result[1] == "*":
232 # symbol definition
233 symdef = result[0] + "\t="
234 result = [symdef] + convert_opcodes(result[2:])
235 else:
236 # label
237 label = result[0]
238 result = convert_opcodes(result[1:])
239 if result:
240 label = label + "\t"
241 return label, result
242
243 def process_line(line):
244 "process a single line of input and return converted version"
245 # remove line ending, if there is one. don't care if NL or CR or combination
246 while len(line) != 0 and (line[-1] == "\r" or line[-1] == "\n"):
247 line = line[:-1]
248 # step 1: split into strings, comments and everything else
249 codeparts, comment = line_preprocess(line)
250 # step 2: if there is anything before comment, process that
251 if codeparts:
252 prefix, codeparts = process_code(codeparts)
253 # reassemble line
254 line = prefix + " ".join(codeparts)
255 else:
256 line = ""
257 if comment:
258 line = line + comment
259 return line + "\n"
260
261 def convert_file(input, output):
262 "convert input file to output file line-by-line"
263 with open(input, "rt") as infile:
264 with open(output, "wt") as outfile:
265 outfile.write(";ACME 0.97\n")
266 for line in infile:
267 outfile.write(process_line(line))
268
269 if __name__ == '__main__':
270 if len(sys.argv) != 3:
271 sys.exit(
272 "Error: wrong number of arguments\n"
273 "\n"
274 "masm2acme.py converts a file from MASM to ACME syntax.\n"
275 "Usage: masm2acme.py INPUTFILE OUTPUTFILE\n"
276 )
277 convert_file(sys.argv[1], sys.argv[2])