-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathvalues.py
688 lines (540 loc) · 21.2 KB
/
values.py
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
"""
Copyright (C) 2013-2020 Craig Thomas
This project uses an MIT style license - see LICENSE for details.
A Color Computer Assembler - see the README.md file for details.
"""
# I M P O R T S ###############################################################
import re
from abc import ABC, abstractmethod
from enum import Enum
from cocoasm.exceptions import ValueTypeError
# C O N S T A N T S ###########################################################
# Pattern to recognize a binary value
BINARY_REGEX = re.compile(
r"^%(?P<value>[01]+)$"
)
# Pattern to recognize a character value
CHAR_REGEX = re.compile(
r"^\'(?P<value>[a-zA-Z\d><'\";:,.#?$%^&*()=!+-/])$"
)
# Pattern to recognize a hex value
HEX_REGEX = re.compile(
r"^\$(?P<value>[\da-fA-F]+)$"
)
# Pattern to recognize an integer value
INT_REGEX = re.compile(
r"^(?P<value>\d+)$"
)
# Pattern to recognize a negative integer value
NEG_INT_REGEX = re.compile(
r"^-(?P<value>\d+)$"
)
# Pattern to recognize a symbol value
SYMBOL_REGEX = re.compile(
r"^(?P<value>[a-zA-Z\d@]+)$"
)
# Patten to recognize an expression
EXPRESSION_REGEX = re.compile(
r"^(?P<left>[$]*\w+)(?P<operation>[+\-/*])(?P<right>[$]*\w+)$"
)
# C L A S S E S ##############################################################
class ExplicitAddressingMode(Enum):
NONE = 0
DIRECT = 1
EXTENDED = 2
RELATIVE = 3
IMMEDIATE = 4
EXTENDED_INDIRECT = 5
EXPLICIT_DIRECT = 6
EXPLICIT_EXTENDED = 7
class ValueType(Enum):
"""
The ValueType enumeration stores what type of value is stored in a
particular class.
"""
UNKNOWN = 0
NUMERIC = 1
STRING = 2
SYMBOL = 3
ADDRESS = 4
NONE = 5
EXPRESSION = 6
LEFT_RIGHT = 7
ADDRESS_EXPRESSION = 8
MULTI_BYTE = 9
MULTI_WORD = 10
class Value(ABC):
"""
A Value stores a basic value recognized by the assembler. Values are
one of several types, being Unknown, Numeric, String, Symbol,
Address, Expression or a special None type.
"""
def __init__(self, value, size_hint=None, mode=ExplicitAddressingMode.NONE):
self.original_string = value
self.type = ValueType.UNKNOWN
self.resolved = True
self.int = 0
self.size_hint = size_hint
self.explict_addressing_mode = mode
self.negative = False
if mode == ExplicitAddressingMode.EXTENDED or mode == ExplicitAddressingMode.EXPLICIT_EXTENDED:
self.size_hint = 4
def __str__(self):
return self.hex()
def ascii(self):
"""
Returns the original ascii representation of the value.
:return: the original ascii representation of the value
"""
return self.original_string
def byte_len(self):
"""
Returns how many bytes are in the hex representation.
:return: the number of hex bytes in the object
"""
return int(self.hex_len() / 2)
def high_byte(self):
if self.hex_len() <= 2:
return 0x00
return int(self.hex()[0:2], 16)
def low_byte(self):
if self.hex_len() == 0:
return 0x00
if self.hex_len() <= 2:
return int(self.hex()[0:2], 16)
return int(self.hex()[2:], 16)
def is_immediate(self):
return self.explict_addressing_mode == ExplicitAddressingMode.IMMEDIATE
def is_direct(self):
return self.explict_addressing_mode == ExplicitAddressingMode.DIRECT
def is_extended(self):
return self.explict_addressing_mode == ExplicitAddressingMode.EXTENDED
def is_explicit_direct(self):
return self.explict_addressing_mode == ExplicitAddressingMode.EXPLICIT_DIRECT
def is_explicit_extended(self):
return self.explict_addressing_mode == ExplicitAddressingMode.EXPLICIT_EXTENDED
def is_none(self):
return self.type == ValueType.NONE
def is_numeric(self):
return self.type == ValueType.NUMERIC
def is_symbol(self):
return self.type == ValueType.SYMBOL
def is_leftright(self):
return self.type == ValueType.LEFT_RIGHT
def is_string(self):
return self.type == ValueType.STRING
def is_address(self):
return self.type == ValueType.ADDRESS
def is_expression(self):
return self.type == ValueType.EXPRESSION
def is_address_expression(self):
return self.type == ValueType.ADDRESS_EXPRESSION
def is_negative(self):
return self.negative
def is_multi_byte(self):
return self.type == ValueType.MULTI_BYTE
def is_multi_word(self):
return self.type == ValueType.MULTI_WORD
def resolve(self, symbol_table):
"""
Attempts to resolve the proper value of the object given the supplied symbol table
:param symbol_table: a dict of symbols mapped to their addresses or values
:return: a new Value type object with the resolved information
"""
return self
@abstractmethod
def hex(self, size=0):
"""
Returns the hex representation of the object.
:return: the hex representation of the object
"""
@abstractmethod
def hex_len(self):
"""
Returns the full length of the hex representation.
:return: the full number of hex characters
"""
@abstractmethod
def is_8_bit(self):
"""
Returns True if the value is an 8-bit integer.
:return: True if the value is an 8-bit integer
"""
@abstractmethod
def is_16_bit(self):
"""
Returns True if the value is a 16-bit integer.
:return: True if the value is a 16-bit integer
"""
@classmethod
def create_from_str(cls, value, instruction=None, default_mode_extended=True):
"""
Parses the value by trying to instantiate various Value classes.
:param value: the string value to parse
:param instruction: the instruction
:param default_mode_extended: True if the default mode should not be Extended, False otherwise
:return: the Value class parsed
"""
original_value = value
if instruction and instruction.is_string_define:
try:
return StringValue(value)
except ValueTypeError:
pass
mode = ExplicitAddressingMode.EXTENDED if default_mode_extended else ExplicitAddressingMode.NONE
if value[0] in [">", "<", "#"]:
if value.startswith("<"):
mode = ExplicitAddressingMode.EXPLICIT_DIRECT
if value.startswith(">"):
mode = ExplicitAddressingMode.EXPLICIT_EXTENDED
if value.startswith("#"):
mode = ExplicitAddressingMode.IMMEDIATE
value = value[1:]
# 16-bit explicit instruction check
size_hint = None
if instruction and instruction.is_16_bit:
size_hint = 4
try:
return ExpressionValue(value, mode=mode)
except ValueTypeError:
pass
try:
return LeftRightValue(value, mode=mode)
except ValueTypeError:
pass
try:
return NumericValue(value, size_hint=size_hint, mode=mode) if size_hint else NumericValue(value, mode=mode)
except ValueTypeError:
pass
try:
return SymbolValue(value, mode=mode)
except ValueTypeError:
pass
raise ValueTypeError("[{}] is an invalid value".format(original_value))
@classmethod
def create_from_byte(cls, byte):
"""
Parses the byte and turns it into a NumericValue.
:param byte: the byte to read
:return: the Value class parsed
"""
if byte == b"":
raise ValueTypeError("No byte available for reading")
return NumericValue(int.from_bytes(byte, byteorder='big'))
@staticmethod
def get_symbol(symbol_label, symbol_table):
if symbol_label not in symbol_table:
raise ValueError("[{}] not in symbol table".format(symbol_label))
return symbol_table[symbol_label]
class NoneValue(Value):
"""
Represents a special None type value that does not store any information.
"""
def __init__(self, value=None):
super().__init__(value)
self.type = ValueType.NONE
self.original_string = ""
def hex(self, size=0):
return ""
def hex_len(self):
return 0
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class MultiByteValue(Value):
def __init__(self, value):
super().__init__(value)
self.hex_array = []
self.type = ValueType.MULTI_BYTE
if "," not in value:
raise ValueTypeError("multi-byte declarations must have a comma in them")
values = value.split(",")
self.hex_array = [NumericValue(x).hex(size=2) for x in values if x != ""]
def hex(self, size=0):
return "".join(self.hex_array)
def hex_len(self):
return len(self.hex())
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class MultiWordValue(Value):
def __init__(self, value):
super().__init__(value)
self.hex_array = []
self.type = ValueType.MULTI_WORD
if "," not in value:
raise ValueTypeError("multi-word declarations must have a comma in them")
values = value.split(",")
self.hex_array = [NumericValue(x).hex(size=4) for x in values if x != ""]
def hex(self, size=0):
return "".join(self.hex_array)
def hex_len(self):
return len(self.hex())
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class StringValue(Value):
"""
Represents a numeric value that can be retrieved as an integer or hex value
string.
"""
def __init__(self, value):
super().__init__(value)
self.hex_array = []
self.type = ValueType.STRING
if value[-1] != value[0]:
raise ValueTypeError("string must begin and end with same delimiter")
self.original_string = value[1:-1]
self.hex_array = ["{:X}".format(ord(x)) for x in value[1:-1]]
def hex(self, size=0):
return "".join(self.hex_array)
def hex_len(self):
return len(self.hex())
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class LeftRightValue(Value):
"""
Represents a value that has both a left hand side and right hand side
that each have separate values.
"""
def __init__(self, value, size_hint=None, mode=ExplicitAddressingMode.NONE):
super().__init__(value, size_hint, mode=mode)
self.type = ValueType.LEFT_RIGHT
if "," not in value:
raise ValueTypeError("[{}] not a left right value".format(value))
if len(value.split(",")) != 2:
raise ValueTypeError("[{}] incorrect number of commas in value".format(value))
self.left, self.right = value.split(",")
def hex(self, size=0):
return ""
def hex_len(self):
return 0
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class NumericValue(Value):
"""
Represents a numeric value that can be retrieved as an integer or hex value
string.
"""
def __init__(self, value, size_hint=None, mode=ExplicitAddressingMode.NONE):
super().__init__(value, size_hint, mode=mode)
self.type = ValueType.NUMERIC
if type(value) == int:
self.int = value
if self.int > 65535:
raise ValueTypeError("integer value cannot exceed 65535")
if self.int < 0:
self.negative = True
self.int *= -1
self.post_init_direct_check()
return
data = CHAR_REGEX.match(value)
if data:
self.int = ord(data.group("value"))
if self.size_hint is None:
self.size_hint = 2
return
data = BINARY_REGEX.match(value)
if data:
bit_length = len(data.group("value"))
if bit_length != 8 and bit_length != 16:
raise ValueTypeError("binary pattern {} must be 8 or 16 bits long".format(data.group("value")))
self.int = int(data.group("value"), 2)
if bit_length == 8 and size_hint is None:
self.size_hint = 2
if self.explict_addressing_mode != ExplicitAddressingMode.IMMEDIATE:
self.explict_addressing_mode = ExplicitAddressingMode.DIRECT
return
data = HEX_REGEX.match(value)
if data:
if len(data.group("value")) > 4:
raise ValueTypeError("hex value length cannot exceed 4 characters")
self.int = int(data.group("value"), 16)
if len(data.group("value")) == 2 and size_hint is None:
self.size_hint = 2
if self.explict_addressing_mode != ExplicitAddressingMode.IMMEDIATE:
self.explict_addressing_mode = ExplicitAddressingMode.DIRECT
if self.explict_addressing_mode == ExplicitAddressingMode.NONE:
self.explict_addressing_mode = ExplicitAddressingMode.EXTENDED
return
data = INT_REGEX.match(value)
if data:
self.int = int(data.group("value"), 10)
if self.int > 65535:
raise ValueTypeError("integer value cannot exceed 65535")
self.post_init_direct_check()
return
data = NEG_INT_REGEX.match(value)
if data:
self.int = int(data.group("value"), 10)
if self.int > 32768:
raise ValueTypeError("integer value cannot be below -32768")
self.negative = True
# self.post_init_direct_check()
return
raise ValueTypeError("[{}] is not valid integer, character literal, or hex value".format(value))
def get_negative(self):
if not self.negative:
return self.int
return 0x100 - self.int if self.int <= 128 else 0x10000 - self.int
def hex(self, size=0):
if self.size_hint and size == 0:
size = self.size_hint
if size == 0:
size = self.hex_len()
size += 1 if size % 2 == 1 else 0
format_specifier = "{{:0>{}X}}".format(size)
return format_specifier.format(self.get_negative())
def hex_len(self):
if self.size_hint is not None:
return self.size_hint
length = len(hex(self.int)[2:])
length += 1 if length % 2 == 1 else 0
return length
def post_init_direct_check(self):
if self.size_hint is None and self.explict_addressing_mode != ExplicitAddressingMode.EXPLICIT_EXTENDED:
if self.int < 256 and self.explict_addressing_mode != ExplicitAddressingMode.IMMEDIATE:
self.size_hint = 2
self.explict_addressing_mode = ExplicitAddressingMode.DIRECT
if self.explict_addressing_mode == ExplicitAddressingMode.NONE:
self.explict_addressing_mode = ExplicitAddressingMode.EXTENDED
def is_4_bit(self):
return self.int <= 16 if self.negative else self.int <= 15
def is_8_bit(self):
return self.int <= 128 if self.negative else self.int <= 127
def is_16_bit(self):
return not self.is_4_bit() and not self.is_8_bit()
class DirectNumericValue(NumericValue):
def __init__(self, value, size_hint=None):
super().__init__(value, size_hint, mode=ExplicitAddressingMode.DIRECT)
class ExtendedNumericValue(NumericValue):
def __init__(self, value, size_hint=None):
super().__init__(value, size_hint, mode=ExplicitAddressingMode.EXTENDED)
class SymbolValue(Value):
"""
Represents a symbol value that stores an address or index.
"""
def __init__(self, value, mode=ExplicitAddressingMode.NONE):
super().__init__(value, mode=mode)
self.value = None
self.resolved = False
self.type = ValueType.SYMBOL
data = SYMBOL_REGEX.match(value)
if not data:
raise ValueTypeError("[{}] is not a valid symbol".format(value))
self.value = value
def hex(self, size=0):
return self.value.hex() if self.resolved else ""
def hex_len(self):
return self.value.hex_len() if self.resolved else 0
def resolve(self, symbol_table):
symbol = self.get_symbol(self.value, symbol_table)
if symbol.is_address():
return AddressValue(symbol.int)
if symbol.is_numeric():
return NumericValue(symbol.int)
def is_8_bit(self):
return False
def is_16_bit(self):
return False
class AddressValue(Value):
"""
Represents a symbol value that stores an index to a statement.
"""
def __init__(self, value, mode=ExplicitAddressingMode.NONE):
super().__init__(value, mode=mode)
self.int = int(value)
self.type = ValueType.ADDRESS
def hex(self, size=0):
if size == 0:
size = self.hex_len()
size += 1 if size % 2 == 1 else 0
format_specifier = "{{:0>{}X}}".format(size)
return format_specifier.format(self.int)
def hex_len(self):
return len(hex(self.int)[2:])
def is_8_bit(self):
return False
def is_16_bit(self):
return True
class ExpressionValue(Value):
"""
A value type that has an expression at its core.
"""
def __init__(self, value, mode=ExplicitAddressingMode.NONE):
super().__init__(value, mode=mode)
self.type = ValueType.EXPRESSION
self.original_value = value
match = EXPRESSION_REGEX.match(value)
if not match:
raise ValueTypeError("[{}] is not a valid expression".format(value))
self.left = Value.create_from_str(match.group("left"), default_mode_extended=False)
self.right = Value.create_from_str(match.group("right"), default_mode_extended=False)
if self.explict_addressing_mode is ExplicitAddressingMode.NONE:
if self.left.is_extended() or self.right.is_extended() or self.left.is_explicit_extended() or self.right.is_explicit_extended():
self.explict_addressing_mode = ExplicitAddressingMode.EXTENDED
self.operation = match.group("operation")
self.value = NoneValue("")
self.resolved = False
def hex(self, size=0):
return "00" if not self.resolved else self.value.hex()
def hex_len(self):
return 0 if not self.resolved else self.value.hex_len()
def resolve(self, symbol_table):
"""
Attempts to resolve the expression using the symbol table supplied. Updates the
main value of the
:param symbol_table: the symbol table to use for resolution
:return: self, or a new Operand class type with a resolved value
"""
if self.left.is_symbol():
self.left = self.get_symbol(self.left.ascii(), symbol_table)
if self.right.is_symbol():
self.right = self.get_symbol(self.right.ascii(), symbol_table)
mode = ExplicitAddressingMode.DIRECT
if self.left.is_extended() or self.left.is_explicit_extended():
mode = ExplicitAddressingMode.EXTENDED
if self.right.is_extended() or self.right.is_explicit_extended():
mode = ExplicitAddressingMode.EXTENDED
if self.right.is_numeric() and self.left.is_numeric():
left = self.left.int
right = self.right.int
if self.operation == "+":
self.value = NumericValue("{}".format(left + right), mode=mode)
if self.operation == "-":
self.value = NumericValue("{}".format(left - right), mode=mode)
if self.operation == "*":
self.value = NumericValue("{}".format(int(left * right)), mode=mode)
if self.operation == "/":
self.value = NumericValue("{}".format(int(left / right)), mode=mode)
return self.value
if self.left.is_address() or self.right.is_address():
self.type = ValueType.ADDRESS_EXPRESSION
return self
raise ValueError("[{}] unresolved expression".format(self.original_value))
def extract_address_index_from_expression(self):
return self.left.int if self.left.is_address() else self.right.int
def calculate_address_offset(self, statements):
address_index = self.left.int if self.left.is_address() else self.right.int
additional_value = self.left.int if self.left.is_numeric() else self.right.int
address = statements[address_index].code_pkg.address.int
if self.operation == "+":
return NumericValue(address + additional_value, size_hint=4, mode=ExplicitAddressingMode.EXTENDED)
elif self.operation == "-":
return NumericValue(address - additional_value, size_hint=4, mode=ExplicitAddressingMode.EXTENDED)
elif self.operation == "*":
return NumericValue(address * additional_value, size_hint=4, mode=ExplicitAddressingMode.EXTENDED)
else:
return NumericValue(int(address / additional_value), size_hint=4, mode=ExplicitAddressingMode.EXTENDED)
def is_8_bit(self):
return False
def is_16_bit(self):
return False
# E N D O F F I L E #######################################################