44
55import math
66import re
7+ from typing import List
78
89from . import errors
910from .errors import InvalidICError as InvalidIC
@@ -217,6 +218,48 @@ def is_int_type(stype):
217218 return stype [0 ] in ('u' , 'i' )
218219
219220
221+ def get_bytes (elements : List [str ]) -> List [str ]:
222+ """ Returns a list a default set of bytes/words in hexadecimal
223+ (starting with an hex number) or literals (starting with #).
224+ Numeric values with more than 2 digits represents a WORD (2 bytes) value.
225+ E.g. '01' => 01h, '001' => 1, 0 bytes (0001h)
226+ Literal values starts with # (1 byte) or ## (2 bytes)
227+ E.g. '#label + 1' => (label + 1) & 0xFF
228+ '##(label + 1)' => (label + 1) & 0xFFFF
229+ """
230+ output = []
231+
232+ for x in elements :
233+ if x .startswith ('##' ): # 2-byte literal
234+ output .append ('({}) & 0xFF' .format (x [2 :]))
235+ output .append ('(({}) >> 8) & 0xFF' .format (x [2 :]))
236+ continue
237+
238+ if x .startswith ('#' ): # 1-byte literal
239+ output .append ('({}) & 0xFF' .format (x [1 :]))
240+ continue
241+
242+ # must be an hex number
243+ assert RE_HEXA .match (x ), 'expected an hex number, got "%s"' % x
244+ output .append ('%02X' % int (x [- 2 :], 16 ))
245+ if len (x ) > 2 :
246+ output .append ('%02X' % int (x [- 4 :- 2 :], 16 ))
247+
248+ return output
249+
250+
251+ def get_bytes_size (elements : List [str ]) -> int :
252+ """ Defines a memory space with a default set of bytes/words in hexadecimal
253+ (starting with an hex number) or literals (starting with #).
254+ Numeric values with more than 2 digits represents a WORD (2 bytes) value.
255+ E.g. '01' => 01h, '001' => 1, 0 bytes (0001h)
256+ Literal values starts with # (1 byte) or ## (2 bytes)
257+ E.g. '#label + 1' => (label + 1) & 0xFF
258+ '##(label + 1)' => (label + 1) & 0xFFFF
259+ """
260+ return len (get_bytes (elements ))
261+
262+
220263# ------------------------------------------------------------------
221264# Typecast conversions
222265# ------------------------------------------------------------------
@@ -559,7 +602,6 @@ def _lvard(ins):
559602 """
560603 output = []
561604
562- l = eval (ins .quad [2 ]) # List of bytes to push
563605 label = tmp_label ()
564606 offset = int (ins .quad [1 ])
565607 tmp = list (ins .quad )
@@ -573,7 +615,7 @@ def _lvard(ins):
573615 output .append ('add hl, bc' )
574616 output .append ('ex de, hl' )
575617 output .append ('ld hl, %s' % label )
576- output .append ('ld bc, %i' % len ( l ))
618+ output .append ('ld bc, %i' % get_bytes_size ( eval ( tmp [ 2 ]) ))
577619 output .append ('ldir' )
578620
579621 return output
0 commit comments