aboutsummaryrefslogtreecommitdiffstats
path: root/asm/creole.py
blob: 8bf609a107e9dacd84a36ab323d4086fd12a0953 (plain) (blame)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# Copyright (c) 2023 Peter McGoron <code@mcgoron.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from enum import Enum

class MalformedArgument(Exception):
	pass

def word_2c(w):
	""" Negate a non-negative integer using 32 bit two's compliment.

	:param w: An integer in two's compliment. A non-negative Python
	integer will work.
	:return: The negation of the integer stored as a two's compliment
	integer.
	"""
	return (~w + 1) & 0xFFFFFFFF
def ti(w):
	""" Explicitly transform integer into two's compliment representation.

	:param w: A python integer.
	:return: The integer in two's compliment.
	"""
	return w if w >= 0 else word_wc(-w)
def from_2c(w):
	""" Turn two's compliment word into Python integer.

	:param w: An integer in 32 bit twos compliment.
	:return: The integer as a proper Python string.
	"""
	if (w >> 31) & 1 == 0:
		return w
	return -word_2c(w)

class Argument:
	""" Class of arguments. Not used directly: It is used to store
	intermediate information during the assembly process. """

	def __init__(self, argtype, val, sign=False):
		""" Initialize an argument.

		:param argtype: Type of the argument (instance of ArgType).
		:param val: Python integer value of the argument.
		:param sign: If the argument should be treated as signed.
		Otherwise, the integer will be interpreted in execution
		as an unsigned integer.
		"""
		self.at = argtype
		self.sign = sign
		self.val = val
	def __str__(self):
		return f'({self.at}, {self.sign}, {self.val})'
	def high_bits(self):
		""" Returns the high bits that the argument would have
		    in the opcode. """
		return int(self.sign) << 1 | (self.at == ArgType.REG)

class ArgType(Enum):
	""" Class denoting the type of an argument to an instruction. """

	IMM = 1
	""" Immediate values are ones that must be numbers (positive or negative). """

	REG = 2
	""" Type of registers. """

	VAL = 3
	""" Type that denotes either immediate values or registers. """

	LAB = 4
	""" Type of labels. """

	def gettype(s):
		""" Parses the type of the argument represented as a string
		    and returns a tuple with the first the first element being
		    the type and the second element being the integer value of
		    the argument.

		    Valid parameters are:

		    * `r` followed by a nonnegative integer (register)
		    * `l` followed by a nonnegative integer (label)
		    * any integer (immediate value)

		    :param s: String representing the argument.
		    :return: The Argument object representing the argument.
		    :raises MalformedArgument:
		"""
		if s.isnumeric():
			return Argument(ArgType.IMM, int(s))
		elif s[0] == "-" and s[1:].isnumeric():
			return Argument(ArgType.IMM, word_2c(int(s[1:])), True)
		elif s[0] == 'r' and s[1:].isnumeric():
			return Argument(ArgType.REG, int(s[1:]))
		elif s[0] == 'l' and s[1:].isnumeric():
			return Argument(ArgType.LAB, int(s[1:]))
		else:
			raise MalformedArgument(s)

	def typecheck(self, s):
		""" Parses the type of the string and returns it if it fits
		    the type of the enum value.

		    :param s: String argument representing an argument.
		    :return: The Argument class containing the object, or None
		    if the string does not fit the type of self. """
		t = ArgType.gettype(s)
		if self == ArgType.VAL:
			if t.at == ArgType.REG or t.at == ArgType.IMM:
				return t
			else:
				return None
		elif t.at == self:
			return t
		else:
			return None

class OpcodeException(Exception):
	pass
class TypecheckLenException(Exception):
	""" Exception thrown when arguments to an instruction are of the
	    incorrect length. """
	def __init__(self, opcode, insargs, argtypelen):
		self.opcode = opcode
		self.insargs = insargs
		self.argtypelen = argtypelen
	def __str__(self):
		return f'''\
arguments {self.insargs} to opcode {self.opcode} not of length {self.argtypelen}\
'''
class TypecheckException(Exception):
	""" Exception thrown when an argument to an instruction are of the
	    incorrect type. """
	def __init__(self, argtype, sarg, i, opcode):
		self.argtype = argtype
		self.sarg = sarg
		self.i = i
		self.opcode = opcode
	def __str__(self):
		return f'''\
opcode {self.opcode} has invalid value {self.sarg}
(expected {self.argtype} in position {self.i})\
'''

class Instruction(Enum):
	""" Class of microcode instructions. The first number is the opcode
	    and the suceeding values are the types of each of the
	    arguments. The first argument is the opcode and the second
	    argument is what function is used to compile the instruction
	    (some instructions are actually versions of other instructions). """
	NOP = 0, "_render_default"
	PUSH = 1, "_render_default", ArgType.VAL
	POP = 2, "_render_default", ArgType.REG
	ADD = 3, "_render_default", ArgType.REG, ArgType.VAL, ArgType.VAL
	MOV = "ADD", "_render_mov", ArgType.REG, ArgType.VAL
	MUL = 4, "_render_default", ArgType.REG, ArgType.VAL, ArgType.VAL
	DIV = 5, "_render_default", ArgType.REG, ArgType.VAL, ArgType.VAL
	SDIV = "DIV", "_render_change_args", ArgType.REG, ArgType.VAL, ArgType.VAL
	SYS = 6, "_render_default", ArgType.VAL
	CLB = 7, "_render_default", ArgType.LAB
	JL = 8, "_render_default", ArgType.LAB, ArgType.VAL, ArgType.VAL
	JLS = "JL", "_render_change_args", ArgType.LAB, ArgType.VAL, ArgType.VAL
	JLE = 9, "_render_default", ArgType.LAB, ArgType.VAL, ArgType.VAL
	JLES = "JLE", "_render_change_args", ArgType.LAB, ArgType.VAL, ArgType.VAL
	JE = 10, "_render_default", ArgType.LAB, ArgType.VAL, ArgType.VAL
	J = "JE", "_render_j", ArgType.LAB
	JNE = 11, "_render_default", ArgType.LAB, ArgType.VAL, ArgType.VAL

	def __int__(self):
		""" Returns the opcode associated with the Instruction.
		    If it is a virtual instruction, it will resolve the string
		    name of the opcode and return its opcode. """
		if type(self.opcode) is int:
			return self.opcode
		return int(Instruction[self.opcode])

	def __init__(self, opcode, renderfun, *args):
		""" Initialize an Instruction. Do not call this function: it is
		    used to make enum values. To add a new instruction, modify
		    the Instruction enum.
		    This function sometimes takes string arguments because
		    certain values may not be loaded until later.

		    :param opcode: Opcode of the instruction, or a string
		    containing the case-sensitive name of the instruction from
		    which this instruction derives from.

		    :param renderfun: a string with the name of a function
		    in the class that returns the instruction opcode.

		    :param *args: Type of each argument to the instruction.
		    The amount of arguments denotes the amount of instructions.
		"""

		if type(opcode) is int and (opcode > 0x7F or opcode < 0):
			raise OpcodeException(opcode)

		self.opcode = opcode
		self.argtypes = args
		self.render = getattr(self, renderfun)

	def typecheck(self, sargs):
		""" Pass arguments to the instruction and check if the
		    arguments are correct.

		    :param sargs: List of arguments to the instruction
		    as strings.
		    :return: List of arguments (as Argument objects).
		    :raises TypeCheckException:
		    :raises TypecheckLenException:
		"""
		rargs = []
		if len(sargs) != len(self.argtypes):
			raise TypecheckLenException(self.opcode, sargs,
			                            len(self.argtypes))
		for i in range(0, len(sargs)):
			t = self.argtypes[i].typecheck(sargs[i])
			if t is None:
				raise TypecheckException(self.argtypes[i],
				                         sargs[i],
				                         i, self.opcode)
			rargs.append(t)
		return rargs

	def _render_mov(self, args):
		args = [args[0], args[1], Argument(ArgType.IMM, 0)]
		return Instruction[self.opcode].render(args)

	def _render_j(self, args):
		args = [args[0], Argument(ArgType.IMM, 0),
		        Argument(ArgType.IMM, 0)]
		return Instruction[self.opcode].render(args)

	def _render_change_args(self, args):
		for i in range(0,len(args)):
			if args[i].at != ArgType.LAB:
				args[i].sign = True
		return Instruction[self.opcode].render(args)

	def _render_default(self, args):
		b = bytes([self.opcode])
		for a in args:
			l = 2 if a.val < 0x80 else None
			bex = encode_pseudo_utf8(a.val, a.high_bits(), l)
			b = b + bex
		return b + bytes([0])

encoding_types = {
#           start      mask   B
	2: (0x7F,       0xC0, 7),
	3: (0xFFF,      0xE0, 12),
	4: (0x1FFFF,    0xF0, 17),
	5: (0x3FFFFF,   0xF8, 22),
	6: (0x7FFFFFF,  0xFC, 27),
	7: (0xFFFFFFFF, 0xFE, 32),
#	B : Total number of bits excluding high bits
}

class InvalidNumberException(Exception):
	pass
class InvalidLengthException(Exception):
	pass
def encode_pseudo_utf8(n, high_bits, to):
	if n < 0:
		raise InvalidNumberException(n)
	if to is None or to < 0:
		for k in sorted(encoding_types):
			if n <= encoding_types[k][0]:
				to = k
				break
		if to is None:
			raise InvalidNumberException(n)
	if to > 8 or to < 0:
		raise InvalidLengthException(to)
	elif to == 1:
		if n < 0x80:
			return bytes([n])
		else:
			raise InvalidNumberException(n,to)

	(maxval, start_byte, n_tot) = encoding_types[to]
	if n > maxval or high_bits > 15:
		raise InvalidNumberException(n, high_bits)
	n = n | (high_bits << n_tot)
	all_bytes = []
	for i in range(0, to - 1):
		all_bytes.append(0x80 | (n & 0x3F))
		n >>= 6
	all_bytes.append(start_byte | n)
	return bytes(reversed(all_bytes))

class RangeCheckException(Exception):
	pass
class Line:
	def __init__(self, ins, args):
		self.ins = ins
		self.args = args

	def check_line(self, lablen, reglen):
		for a in self.args:
			if a.at == ArgType.REG:
				if a.val < 0 or a.val >= reglen:
					raise RangeCheckException(a.at,
					                          a.val,
					                          reglen)
			elif a.at == ArgType.LAB:
				if a.val < 0 or a.val >= lablen:
					raise RangeCheckException(a.at,
					                          a.val,
					                          reglen)

	def __call__(self):
		return self.ins.render(self.args)

class InstructionNotFoundException(Exception):
	pass
class Program:
	def asm_push_line(self, ins, args):
		l = Line(ins, args)
		l.check_line(self.lablen, self.reglen)
		self.asm.append(l)

	def parse_asm_line(self, line):
		line = line.split()
		line[0] = line[0].casefold()
		try:
			# TODO: is there no better way to do this in Python?
			ins = Instruction[line[0].upper()]
		except Exception as e:
			raise InstructionNotFoundException(line[0])

		args_w_type = ins.typecheck(line[1:])
		self.asm_push_line(ins, args_w_type)

	def parse_lines(self, lines):
		for l in lines:
			self.parse_asm_line(l)

	def __call__(self):
		b = bytes()
		for line in self.asm:
			b = b + line()
		return b

	def __init__(self, lablen=16, reglen=16):
		self.asm = []
		self.lablen = lablen
		self.reglen = reglen