repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
boriel/zxbasic | arch/zx48k/optimizer.py | initialize_memory | def initialize_memory(basic_block):
""" Initializes global memory array with the given one
"""
global MEMORY
MEMORY = basic_block.mem
get_labels(MEMORY, basic_block)
basic_block.mem = MEMORY | python | def initialize_memory(basic_block):
""" Initializes global memory array with the given one
"""
global MEMORY
MEMORY = basic_block.mem
get_labels(MEMORY, basic_block)
basic_block.mem = MEMORY | Initializes global memory array with the given one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L2182-L2189 |
boriel/zxbasic | arch/zx48k/optimizer.py | cleanupmem | def cleanupmem(initial_memory):
""" Cleans up initial memory. Each label must be
ALONE. Each instruction must have an space, etc...
"""
i = 0
while i < len(initial_memory):
tmp = initial_memory[i]
match = RE_LABEL.match(tmp)
if not match:
i += 1
continue
if tmp.rstrip() == match.group():
i += 1
continue
initial_memory[i] = tmp[match.end():]
initial_memory.insert(i, match.group())
i += 1 | python | def cleanupmem(initial_memory):
""" Cleans up initial memory. Each label must be
ALONE. Each instruction must have an space, etc...
"""
i = 0
while i < len(initial_memory):
tmp = initial_memory[i]
match = RE_LABEL.match(tmp)
if not match:
i += 1
continue
if tmp.rstrip() == match.group():
i += 1
continue
initial_memory[i] = tmp[match.end():]
initial_memory.insert(i, match.group())
i += 1 | Cleans up initial memory. Each label must be
ALONE. Each instruction must have an space, etc... | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L2223-L2241 |
boriel/zxbasic | arch/zx48k/optimizer.py | cleanup_local_labels | def cleanup_local_labels(block):
""" Traverses memory, to make any local label a unique
global one. At this point there's only a single code
block
"""
global PROC_COUNTER
stack = [[]]
hashes = [{}]
stackprc = [PROC_COUNTER]
used = [{}] # List of hashes of unresolved labels per scope
MEMORY = block.mem
for cell in MEMORY:
if cell.inst.upper() == 'PROC':
stack += [[]]
hashes += [{}]
stackprc += [PROC_COUNTER]
used += [{}]
PROC_COUNTER += 1
continue
if cell.inst.upper() == 'ENDP':
if len(stack) > 1: # There might be unbalanced stack due to syntax errors
for label in used[-1].keys():
if label in stack[-1]:
newlabel = hashes[-1][label]
for cell in used[-1][label]:
cell.replace_label(label, newlabel)
stack.pop()
hashes.pop()
stackprc.pop()
used.pop()
continue
tmp = cell.asm.strip()
if tmp.upper()[:5] == 'LOCAL':
tmp = tmp[5:].split(',')
for lbl in tmp:
lbl = lbl.strip()
if lbl in stack[-1]:
continue
stack[-1] += [lbl]
hashes[-1][lbl] = 'PROC%i.' % stackprc[-1] + lbl
if used[-1].get(lbl, None) is None:
used[-1][lbl] = []
cell.asm = ';' + cell.asm # Remove it
continue
if cell.is_label:
label = cell.inst
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
label = hashes[i][label]
cell.asm = label + ':'
break
continue
for label in cell.used_labels:
labelUsed = False
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
newlabel = hashes[i][label]
cell.replace_label(label, newlabel)
labelUsed = True
break
if not labelUsed:
if used[-1].get(label, None) is None:
used[-1][label] = []
used[-1][label] += [cell]
for i in range(len(MEMORY) - 1, -1, -1):
if MEMORY[i].asm[0] == ';':
MEMORY.pop(i)
block.mem = MEMORY
block.asm = [x.asm for x in MEMORY if len(x.asm.strip())] | python | def cleanup_local_labels(block):
""" Traverses memory, to make any local label a unique
global one. At this point there's only a single code
block
"""
global PROC_COUNTER
stack = [[]]
hashes = [{}]
stackprc = [PROC_COUNTER]
used = [{}] # List of hashes of unresolved labels per scope
MEMORY = block.mem
for cell in MEMORY:
if cell.inst.upper() == 'PROC':
stack += [[]]
hashes += [{}]
stackprc += [PROC_COUNTER]
used += [{}]
PROC_COUNTER += 1
continue
if cell.inst.upper() == 'ENDP':
if len(stack) > 1: # There might be unbalanced stack due to syntax errors
for label in used[-1].keys():
if label in stack[-1]:
newlabel = hashes[-1][label]
for cell in used[-1][label]:
cell.replace_label(label, newlabel)
stack.pop()
hashes.pop()
stackprc.pop()
used.pop()
continue
tmp = cell.asm.strip()
if tmp.upper()[:5] == 'LOCAL':
tmp = tmp[5:].split(',')
for lbl in tmp:
lbl = lbl.strip()
if lbl in stack[-1]:
continue
stack[-1] += [lbl]
hashes[-1][lbl] = 'PROC%i.' % stackprc[-1] + lbl
if used[-1].get(lbl, None) is None:
used[-1][lbl] = []
cell.asm = ';' + cell.asm # Remove it
continue
if cell.is_label:
label = cell.inst
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
label = hashes[i][label]
cell.asm = label + ':'
break
continue
for label in cell.used_labels:
labelUsed = False
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
newlabel = hashes[i][label]
cell.replace_label(label, newlabel)
labelUsed = True
break
if not labelUsed:
if used[-1].get(label, None) is None:
used[-1][label] = []
used[-1][label] += [cell]
for i in range(len(MEMORY) - 1, -1, -1):
if MEMORY[i].asm[0] == ';':
MEMORY.pop(i)
block.mem = MEMORY
block.asm = [x.asm for x in MEMORY if len(x.asm.strip())] | Traverses memory, to make any local label a unique
global one. At this point there's only a single code
block | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L2261-L2342 |
boriel/zxbasic | arch/zx48k/optimizer.py | optimize | def optimize(initial_memory):
""" This will remove useless instructions
"""
global BLOCKS
global PROC_COUNTER
LABELS.clear()
JUMP_LABELS.clear()
del MEMORY[:]
PROC_COUNTER = 0
cleanupmem(initial_memory)
if OPTIONS.optimization.value <= 2:
return '\n'.join(x for x in initial_memory if not RE_PRAGMA.match(x))
optimize_init()
bb = BasicBlock(initial_memory)
cleanup_local_labels(bb)
initialize_memory(bb)
BLOCKS = basic_blocks = get_basic_blocks(bb) # 1st partition the Basic Blocks
for x in basic_blocks:
x.clean_up_comes_from()
x.clean_up_goes_to()
for x in basic_blocks:
x.update_goes_and_comes()
LABELS['*START*'].basic_block.add_goes_to(basic_blocks[0])
LABELS['*START*'].basic_block.next = basic_blocks[0]
basic_blocks[0].prev = LABELS['*START*'].basic_block
LABELS[END_PROGRAM_LABEL].basic_block.add_goes_to(LABELS['*__END_PROGRAM*'].basic_block)
for x in basic_blocks:
x.optimize()
for x in basic_blocks:
if x.comes_from == [] and len([y for y in JUMP_LABELS if x is LABELS[y].basic_block]):
x.ignored = True
return '\n'.join([y for y in flatten_list([x.asm for x in basic_blocks if not x.ignored])
if not RE_PRAGMA.match(y)]) | python | def optimize(initial_memory):
""" This will remove useless instructions
"""
global BLOCKS
global PROC_COUNTER
LABELS.clear()
JUMP_LABELS.clear()
del MEMORY[:]
PROC_COUNTER = 0
cleanupmem(initial_memory)
if OPTIONS.optimization.value <= 2:
return '\n'.join(x for x in initial_memory if not RE_PRAGMA.match(x))
optimize_init()
bb = BasicBlock(initial_memory)
cleanup_local_labels(bb)
initialize_memory(bb)
BLOCKS = basic_blocks = get_basic_blocks(bb) # 1st partition the Basic Blocks
for x in basic_blocks:
x.clean_up_comes_from()
x.clean_up_goes_to()
for x in basic_blocks:
x.update_goes_and_comes()
LABELS['*START*'].basic_block.add_goes_to(basic_blocks[0])
LABELS['*START*'].basic_block.next = basic_blocks[0]
basic_blocks[0].prev = LABELS['*START*'].basic_block
LABELS[END_PROGRAM_LABEL].basic_block.add_goes_to(LABELS['*__END_PROGRAM*'].basic_block)
for x in basic_blocks:
x.optimize()
for x in basic_blocks:
if x.comes_from == [] and len([y for y in JUMP_LABELS if x is LABELS[y].basic_block]):
x.ignored = True
return '\n'.join([y for y in flatten_list([x.asm for x in basic_blocks if not x.ignored])
if not RE_PRAGMA.match(y)]) | This will remove useless instructions | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L2345-L2388 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.reset | def reset(self):
""" Initial state
"""
self.regs = {}
self.stack = []
self.mem = defaultdict(new_tmp_val) # Dict of label -> value in memory
for i in 'abcdefhl':
self.regs[i] = new_tmp_val() # Initial unknown state
self.regs["%s'" % i] = new_tmp_val()
self.regs['ixh'] = new_tmp_val()
self.regs['ixl'] = new_tmp_val()
self.regs['iyh'] = new_tmp_val()
self.regs['iyl'] = new_tmp_val()
self.regs['sp'] = new_tmp_val()
self.regs['r'] = new_tmp_val()
self.regs['i'] = new_tmp_val()
self.regs['af'] = new_tmp_val()
self.regs['bc'] = new_tmp_val()
self.regs['de'] = new_tmp_val()
self.regs['hl'] = new_tmp_val()
self.regs['ix'] = new_tmp_val()
self.regs['iy'] = new_tmp_val()
self.regs["af'"] = new_tmp_val()
self.regs["bc'"] = new_tmp_val()
self.regs["de'"] = new_tmp_val()
self.regs["hl'"] = new_tmp_val()
self._16bit = {'b': 'bc', 'c': 'bc', 'd': 'de', 'e': 'de', 'h': 'hl', 'l': 'hl',
"b'": "bc'", "c'": "bc'", "d'": "de'", "e'": "de'", "h'": "hl'", "l'": "hl'",
'ixy': 'ix', 'ixl': 'ix', 'iyh': 'iy', 'iyl': 'iy', 'a': 'af', "a'": "af'",
'f': 'af', "f'": "af'"}
self.reset_flags() | python | def reset(self):
""" Initial state
"""
self.regs = {}
self.stack = []
self.mem = defaultdict(new_tmp_val) # Dict of label -> value in memory
for i in 'abcdefhl':
self.regs[i] = new_tmp_val() # Initial unknown state
self.regs["%s'" % i] = new_tmp_val()
self.regs['ixh'] = new_tmp_val()
self.regs['ixl'] = new_tmp_val()
self.regs['iyh'] = new_tmp_val()
self.regs['iyl'] = new_tmp_val()
self.regs['sp'] = new_tmp_val()
self.regs['r'] = new_tmp_val()
self.regs['i'] = new_tmp_val()
self.regs['af'] = new_tmp_val()
self.regs['bc'] = new_tmp_val()
self.regs['de'] = new_tmp_val()
self.regs['hl'] = new_tmp_val()
self.regs['ix'] = new_tmp_val()
self.regs['iy'] = new_tmp_val()
self.regs["af'"] = new_tmp_val()
self.regs["bc'"] = new_tmp_val()
self.regs["de'"] = new_tmp_val()
self.regs["hl'"] = new_tmp_val()
self._16bit = {'b': 'bc', 'c': 'bc', 'd': 'de', 'e': 'de', 'h': 'hl', 'l': 'hl',
"b'": "bc'", "c'": "bc'", "d'": "de'", "e'": "de'", "h'": "hl'", "l'": "hl'",
'ixy': 'ix', 'ixl': 'ix', 'iyh': 'iy', 'iyl': 'iy', 'a': 'af', "a'": "af'",
'f': 'af', "f'": "af'"}
self.reset_flags() | Initial state | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L373-L410 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.reset_flags | def reset_flags(self):
""" Resets flags to an "unknown state"
"""
self.C = None
self.Z = None
self.P = None
self.S = None | python | def reset_flags(self):
""" Resets flags to an "unknown state"
"""
self.C = None
self.Z = None
self.P = None
self.S = None | Resets flags to an "unknown state" | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L412-L418 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.get | def get(self, r):
""" Returns precomputed value of the given expression
"""
if r is None:
return None
if r.lower() == '(sp)' and self.stack:
return self.stack[-1]
if r[:1] == '(':
return self.mem[r[1:-1]]
r = r.lower()
if is_number(r):
return str(valnum(r))
if not is_register(r):
return None
return self.regs[r] | python | def get(self, r):
""" Returns precomputed value of the given expression
"""
if r is None:
return None
if r.lower() == '(sp)' and self.stack:
return self.stack[-1]
if r[:1] == '(':
return self.mem[r[1:-1]]
r = r.lower()
if is_number(r):
return str(valnum(r))
if not is_register(r):
return None
return self.regs[r] | Returns precomputed value of the given expression | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L503-L522 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.getv | def getv(self, r):
""" Like the above, but returns the <int> value.
"""
v = self.get(r)
if not is_unknown(v):
try:
v = int(v)
except ValueError:
v = None
else:
v = None
return v | python | def getv(self, r):
""" Like the above, but returns the <int> value.
"""
v = self.get(r)
if not is_unknown(v):
try:
v = int(v)
except ValueError:
v = None
else:
v = None
return v | Like the above, but returns the <int> value. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L524-L535 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.eq | def eq(self, r1, r2):
""" True if values of r1 and r2 registers are equal
"""
if not is_register(r1) or not is_register(r2):
return False
if self.regs[r1] is None or self.regs[r2] is None: # HINT: This's been never USED??
return False
return self.regs[r1] == self.regs[r2] | python | def eq(self, r1, r2):
""" True if values of r1 and r2 registers are equal
"""
if not is_register(r1) or not is_register(r2):
return False
if self.regs[r1] is None or self.regs[r2] is None: # HINT: This's been never USED??
return False
return self.regs[r1] == self.regs[r2] | True if values of r1 and r2 registers are equal | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L537-L546 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.inc | def inc(self, r):
""" Does inc on the register and precomputes flags
"""
self.set_flag(None)
if not is_register(r):
if r[0] == '(': # a memory position, basically: inc(hl)
r_ = r[1:-1].strip()
v_ = self.getv(self.mem.get(r_, None))
if v_ is not None:
v_ = (v_ + 1) & 0xFF
self.mem[r_] = str(v_)
self.Z = int(v_ == 0) # HINT: This might be improved
else:
self.mem[r_] = new_tmp_val()
return
if self.getv(r) is not None:
self.set(r, self.getv(r) + 1)
else:
self.set(r, None) | python | def inc(self, r):
""" Does inc on the register and precomputes flags
"""
self.set_flag(None)
if not is_register(r):
if r[0] == '(': # a memory position, basically: inc(hl)
r_ = r[1:-1].strip()
v_ = self.getv(self.mem.get(r_, None))
if v_ is not None:
v_ = (v_ + 1) & 0xFF
self.mem[r_] = str(v_)
self.Z = int(v_ == 0) # HINT: This might be improved
else:
self.mem[r_] = new_tmp_val()
return
if self.getv(r) is not None:
self.set(r, self.getv(r) + 1)
else:
self.set(r, None) | Does inc on the register and precomputes flags | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L561-L581 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.rrc | def rrc(self, r):
""" Does a ROTATION to the RIGHT |>>
"""
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.regs[r] = str((v_ >> 1) | ((v_ & 1) << 7)) | python | def rrc(self, r):
""" Does a ROTATION to the RIGHT |>>
"""
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.regs[r] = str((v_ >> 1) | ((v_ & 1) << 7)) | Does a ROTATION to the RIGHT |>> | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L605-L614 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.rr | def rr(self, r):
""" Like the above, bus uses carry
"""
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rrc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ >> 7
self.regs[r] = str((v_ & 0x7F) | (tmp << 7)) | python | def rr(self, r):
""" Like the above, bus uses carry
"""
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rrc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ >> 7
self.regs[r] = str((v_ & 0x7F) | (tmp << 7)) | Like the above, bus uses carry | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L616-L628 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.rlc | def rlc(self, r):
""" Does a ROTATION to the LEFT <<|
"""
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.set(r, ((v_ << 1) & 0xFF) | (v_ >> 7)) | python | def rlc(self, r):
""" Does a ROTATION to the LEFT <<|
"""
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.set(r, ((v_ << 1) & 0xFF) | (v_ >> 7)) | Does a ROTATION to the LEFT <<| | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L630-L639 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.rl | def rl(self, r):
""" Like the above, bus uses carry
"""
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rlc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ & 1
self.regs[r] = str((v_ & 0xFE) | tmp) | python | def rl(self, r):
""" Like the above, bus uses carry
"""
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rlc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ & 1
self.regs[r] = str((v_ & 0xFE) | tmp) | Like the above, bus uses carry | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L641-L653 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers._is | def _is(self, r, val):
""" True if value of r is val.
"""
if not is_register(r) or val is None:
return False
r = r.lower()
if is_register(val):
return self.eq(r, val)
if is_number(val):
val = str(valnum(val))
else:
val = str(val)
if val[0] == '(':
val = self.mem[val[1:-1]]
return self.regs[r] == val | python | def _is(self, r, val):
""" True if value of r is val.
"""
if not is_register(r) or val is None:
return False
r = r.lower()
if is_register(val):
return self.eq(r, val)
if is_number(val):
val = str(valnum(val))
else:
val = str(val)
if val[0] == '(':
val = self.mem[val[1:-1]]
return self.regs[r] == val | True if value of r is val. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L655-L673 |
boriel/zxbasic | arch/zx48k/optimizer.py | Registers.op | def op(self, i, o):
""" Tries to update the registers values with the given
instruction.
"""
for ii in range(len(o)):
if is_register(o[ii]):
o[ii] = o[ii].lower()
if i == 'ld':
self.set(o[0], o[1])
return
if i == 'push':
if valnum(self.regs['sp']):
self.set('sp', (self.getv(self.regs['sp']) - 2) % 0xFFFF)
else:
self.set('sp', None)
self.stack.append(self.regs[o[0]])
return
if i == 'pop':
self.set(o[0], self.stack and self.stack.pop() or None)
if valnum(self.regs['sp']):
self.set('sp', (self.getv(self.regs['sp']) + 2) % 0xFFFF)
else:
self.set('sp', None)
return
if i == 'inc':
self.inc(o[0])
return
if i == 'dec':
self.dec(o[0])
return
if i == 'rra':
self.rr('a')
return
if i == 'rla':
self.rl('a')
return
if i == 'rlca':
self.rlc('a')
return
if i == 'rrca':
self.rrc('a')
return
if i == 'rr':
self.rr(o[0])
return
if i == 'rl':
self.rl(o[0])
return
if i == 'exx':
tmp = self.regs['bc']
self.set('bc', "bc'")
self.set("bc'", tmp)
tmp = self.regs['de']
self.set('de', "de'")
self.set("de'", tmp)
tmp = self.regs['hl']
self.set('hl', "hl'")
self.set("hl'", tmp)
return
if i == 'ex':
tmp = self.get(o[1])
self.set(o[1], o[0])
self.set(o[0], tmp)
return
if i == 'xor':
self.C = 0
if o[0] == 'a':
self.set('a', 0)
self.Z = 1
return
if self.getv('a') is None or self.getv(o[0]) is None:
self.Z = None
self.set('a', None)
return
self.set('a', self.getv('a') ^ self.getv(o[0]))
self.Z = int(self.get('a') == 0)
return
if i in ('or', 'and'):
self.C = 0
if self.getv('a') is None or self.getv(o[0]) is None:
self.Z = None
self.set('a', None)
return
if i == 'or':
self.set('a', self.getv('a') | self.getv(o[0]))
else:
self.set('a', self.getv('a') & self.getv(o[0]))
self.Z = int(self.get('a') == 0)
return
if i in ('adc', 'sbc'):
if len(o) == 1:
o = ['a', o[0]]
if self.C is None:
self.set(o[0], 'None')
self.Z = None
self.set(o[0], None)
return
if i == 'sbc' and o[0] == o[1]:
self.Z = int(not self.C)
self.set(o[0], -self.C)
return
if self.getv(o[0]) is None or self.getv(o[1]) is None:
self.set_flag(None)
self.set(o[0], None)
return
if i == 'adc':
val = self.getv(o[0]) + self.getv(o[1]) + self.C
if is_8bit_register(o[0]):
self.C = int(val > 0xFF)
else:
self.C = int(val > 0xFFFF)
self.set(o[0], val)
return
val = self.getv(o[0]) - self.getv(o[1]) - self.C
self.C = int(val < 0)
self.Z = int(val == 0)
self.set(o[0], val)
return
if i in ('add', 'sub'):
if len(o) == 1:
o = ['a', o[0]]
if i == 'sub' and o[0] == o[1]:
self.Z = 1
self.C = 0
self.set(o[0], 0)
return
if not is_number(self.get(o[0])) or not is_number(self.get(o[1])) is None:
self.set_flag(None)
self.set(o[0], None)
return
if i == 'add':
val = self.getv(o[0]) + self.getv(o[1])
if is_8bit_register(o[0]):
self.C = int(val > 0xFF)
val &= 0xFF
self.Z = int(val == 0)
self.S = val >> 7
else:
self.C = int(val > 0xFFFF)
val &= 0xFFFF
self.set(o[0], val)
return
val = self.getv(o[0]) - self.getv(o[1])
if is_8bit_register(o[0]):
self.C = int(val < 0)
val &= 0xFF
self.Z = int(val == 0)
self.S = val >> 7
else:
self.C = int(val < 0)
val &= 0xFFFF
self.set(o[0], val)
return
if i == 'neg':
if self.getv('a') is None:
self.set_flag(None)
return
val = -self.getv('a')
self.set('a', val)
self.Z = int(not val)
val &= 0xFF
self.S = val >> 7
return
if i == 'scf':
self.C = 1
return
if i == 'ccf':
if self.C is not None:
self.C = int(not self.C)
return
if i == 'cpl':
if self.getv('a') is None:
return
self.set('a', 0xFF ^ self.getv('a'))
return
# Unknown. Resets ALL
self.reset() | python | def op(self, i, o):
""" Tries to update the registers values with the given
instruction.
"""
for ii in range(len(o)):
if is_register(o[ii]):
o[ii] = o[ii].lower()
if i == 'ld':
self.set(o[0], o[1])
return
if i == 'push':
if valnum(self.regs['sp']):
self.set('sp', (self.getv(self.regs['sp']) - 2) % 0xFFFF)
else:
self.set('sp', None)
self.stack.append(self.regs[o[0]])
return
if i == 'pop':
self.set(o[0], self.stack and self.stack.pop() or None)
if valnum(self.regs['sp']):
self.set('sp', (self.getv(self.regs['sp']) + 2) % 0xFFFF)
else:
self.set('sp', None)
return
if i == 'inc':
self.inc(o[0])
return
if i == 'dec':
self.dec(o[0])
return
if i == 'rra':
self.rr('a')
return
if i == 'rla':
self.rl('a')
return
if i == 'rlca':
self.rlc('a')
return
if i == 'rrca':
self.rrc('a')
return
if i == 'rr':
self.rr(o[0])
return
if i == 'rl':
self.rl(o[0])
return
if i == 'exx':
tmp = self.regs['bc']
self.set('bc', "bc'")
self.set("bc'", tmp)
tmp = self.regs['de']
self.set('de', "de'")
self.set("de'", tmp)
tmp = self.regs['hl']
self.set('hl', "hl'")
self.set("hl'", tmp)
return
if i == 'ex':
tmp = self.get(o[1])
self.set(o[1], o[0])
self.set(o[0], tmp)
return
if i == 'xor':
self.C = 0
if o[0] == 'a':
self.set('a', 0)
self.Z = 1
return
if self.getv('a') is None or self.getv(o[0]) is None:
self.Z = None
self.set('a', None)
return
self.set('a', self.getv('a') ^ self.getv(o[0]))
self.Z = int(self.get('a') == 0)
return
if i in ('or', 'and'):
self.C = 0
if self.getv('a') is None or self.getv(o[0]) is None:
self.Z = None
self.set('a', None)
return
if i == 'or':
self.set('a', self.getv('a') | self.getv(o[0]))
else:
self.set('a', self.getv('a') & self.getv(o[0]))
self.Z = int(self.get('a') == 0)
return
if i in ('adc', 'sbc'):
if len(o) == 1:
o = ['a', o[0]]
if self.C is None:
self.set(o[0], 'None')
self.Z = None
self.set(o[0], None)
return
if i == 'sbc' and o[0] == o[1]:
self.Z = int(not self.C)
self.set(o[0], -self.C)
return
if self.getv(o[0]) is None or self.getv(o[1]) is None:
self.set_flag(None)
self.set(o[0], None)
return
if i == 'adc':
val = self.getv(o[0]) + self.getv(o[1]) + self.C
if is_8bit_register(o[0]):
self.C = int(val > 0xFF)
else:
self.C = int(val > 0xFFFF)
self.set(o[0], val)
return
val = self.getv(o[0]) - self.getv(o[1]) - self.C
self.C = int(val < 0)
self.Z = int(val == 0)
self.set(o[0], val)
return
if i in ('add', 'sub'):
if len(o) == 1:
o = ['a', o[0]]
if i == 'sub' and o[0] == o[1]:
self.Z = 1
self.C = 0
self.set(o[0], 0)
return
if not is_number(self.get(o[0])) or not is_number(self.get(o[1])) is None:
self.set_flag(None)
self.set(o[0], None)
return
if i == 'add':
val = self.getv(o[0]) + self.getv(o[1])
if is_8bit_register(o[0]):
self.C = int(val > 0xFF)
val &= 0xFF
self.Z = int(val == 0)
self.S = val >> 7
else:
self.C = int(val > 0xFFFF)
val &= 0xFFFF
self.set(o[0], val)
return
val = self.getv(o[0]) - self.getv(o[1])
if is_8bit_register(o[0]):
self.C = int(val < 0)
val &= 0xFF
self.Z = int(val == 0)
self.S = val >> 7
else:
self.C = int(val < 0)
val &= 0xFFFF
self.set(o[0], val)
return
if i == 'neg':
if self.getv('a') is None:
self.set_flag(None)
return
val = -self.getv('a')
self.set('a', val)
self.Z = int(not val)
val &= 0xFF
self.S = val >> 7
return
if i == 'scf':
self.C = 1
return
if i == 'ccf':
if self.C is not None:
self.C = int(not self.C)
return
if i == 'cpl':
if self.getv('a') is None:
return
self.set('a', 0xFF ^ self.getv('a'))
return
# Unknown. Resets ALL
self.reset() | Tries to update the registers values with the given
instruction. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L675-L887 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.opers | def opers(self):
""" Returns a list of operators this mnemonic uses
"""
i = [x for x in self.asm.strip(' \t\n').split(' ') if x != '']
if len(i) == 1:
return []
i = ''.join(i[1:]).split(',')
if self.condition_flag is not None:
i = i[1:]
else:
i = i[0:]
op = [x.lower() if is_register(x) else x for x in i]
return op | python | def opers(self):
""" Returns a list of operators this mnemonic uses
"""
i = [x for x in self.asm.strip(' \t\n').split(' ') if x != '']
if len(i) == 1:
return []
i = ''.join(i[1:]).split(',')
if self.condition_flag is not None:
i = i[1:]
else:
i = i[0:]
op = [x.lower() if is_register(x) else x for x in i]
return op | Returns a list of operators this mnemonic uses | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L948-L963 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.destroys | def destroys(self):
""" Returns which single registers (including f, flag)
this instruction changes.
Registers are: a, b, c, d, e, i, h, l, ixh, ixl, iyh, iyl, r
LD a, X => Destroys a
LD a, a => Destroys nothing
INC a => Destroys a, f
POP af => Destroys a, f, sp
PUSH af => Destroys sp
ret => Destroys SP
"""
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
res = set([])
i = self.inst
o = self.opers
if i in {'push', 'ret', 'call', 'rst', 'reti', 'retn'}:
return ['sp']
if i == 'pop':
res.update('sp', single_registers(o[:1]))
elif i in {'ldi', 'ldir', 'ldd', 'lddr'}:
res.update('a', 'b', 'c', 'd', 'e', 'f')
elif i in {'otir', 'otdr', 'oti', 'otd', 'inir', 'indr', 'ini', 'ind'}:
res.update('h', 'l', 'b')
elif i in {'cpir', 'cpi', 'cpdr', 'cpd'}:
res.update('h', 'l', 'b', 'c', 'f')
elif i in ('ld', 'in'):
res.update(single_registers(o[:1]))
elif i in ('inc', 'dec'):
res.update('f', single_registers(o[:1]))
elif i == 'exx':
res.update('b', 'c', 'd', 'e', 'h', 'l')
elif i == 'ex':
res.update(single_registers(o[0]))
res.update(single_registers(o[1]))
elif i in {'ccf', 'scf', 'bit', 'cp'}:
res.add('f')
elif i in {'or', 'and', 'xor', 'add', 'adc', 'sub', 'sbc'}:
if len(o) > 1:
res.update(single_registers(o[0]))
else:
res.add('a')
res.add('f')
elif i in {'neg', 'cpl', 'daa', 'rra', 'rla', 'rrca', 'rlca', 'rrd', 'rld'}:
res.update('a', 'f')
elif i == 'djnz':
res.update('b', 'f')
elif i in {'rr', 'rl', 'rrc', 'rlc', 'srl', 'sra', 'sll', 'sla'}:
res.update(single_registers(o[0]))
res.add('f')
elif i in ('set', 'res'):
res.update(single_registers(o[1]))
return list(res) | python | def destroys(self):
""" Returns which single registers (including f, flag)
this instruction changes.
Registers are: a, b, c, d, e, i, h, l, ixh, ixl, iyh, iyl, r
LD a, X => Destroys a
LD a, a => Destroys nothing
INC a => Destroys a, f
POP af => Destroys a, f, sp
PUSH af => Destroys sp
ret => Destroys SP
"""
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
res = set([])
i = self.inst
o = self.opers
if i in {'push', 'ret', 'call', 'rst', 'reti', 'retn'}:
return ['sp']
if i == 'pop':
res.update('sp', single_registers(o[:1]))
elif i in {'ldi', 'ldir', 'ldd', 'lddr'}:
res.update('a', 'b', 'c', 'd', 'e', 'f')
elif i in {'otir', 'otdr', 'oti', 'otd', 'inir', 'indr', 'ini', 'ind'}:
res.update('h', 'l', 'b')
elif i in {'cpir', 'cpi', 'cpdr', 'cpd'}:
res.update('h', 'l', 'b', 'c', 'f')
elif i in ('ld', 'in'):
res.update(single_registers(o[:1]))
elif i in ('inc', 'dec'):
res.update('f', single_registers(o[:1]))
elif i == 'exx':
res.update('b', 'c', 'd', 'e', 'h', 'l')
elif i == 'ex':
res.update(single_registers(o[0]))
res.update(single_registers(o[1]))
elif i in {'ccf', 'scf', 'bit', 'cp'}:
res.add('f')
elif i in {'or', 'and', 'xor', 'add', 'adc', 'sub', 'sbc'}:
if len(o) > 1:
res.update(single_registers(o[0]))
else:
res.add('a')
res.add('f')
elif i in {'neg', 'cpl', 'daa', 'rra', 'rla', 'rrca', 'rlca', 'rrd', 'rld'}:
res.update('a', 'f')
elif i == 'djnz':
res.update('b', 'f')
elif i in {'rr', 'rl', 'rrc', 'rlc', 'srl', 'sra', 'sll', 'sla'}:
res.update(single_registers(o[0]))
res.add('f')
elif i in ('set', 'res'):
res.update(single_registers(o[1]))
return list(res) | Returns which single registers (including f, flag)
this instruction changes.
Registers are: a, b, c, d, e, i, h, l, ixh, ixl, iyh, iyl, r
LD a, X => Destroys a
LD a, a => Destroys nothing
INC a => Destroys a, f
POP af => Destroys a, f, sp
PUSH af => Destroys sp
ret => Destroys SP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L966-L1027 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.requires | def requires(self):
""" Returns the registers, operands, etc. required by an instruction.
"""
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
if self.inst == '#pragma':
tmp = self.__instr.split(' ')[1:]
if tmp[0] != 'opt':
return
if tmp[1] == 'require':
return set(flatten_list([single_registers(x.strip(', \t\r')) for x in tmp[2:]]))
return set([])
result = set([])
i = self.inst
o = [x.lower() for x in self.opers]
if i in ['ret', 'pop', 'push']:
result.add('sp')
if self.condition_flag is not None or i in ['sbc', 'adc']:
result.add('f')
for O in o:
if '(hl)' in O:
result.add('h')
result.add('l')
if '(de)' in O:
result.add('d')
result.add('e')
if '(bc)' in O:
result.add('b')
result.add('c')
if '(sp)' in O:
result.add('sp')
if '(ix' in O:
result.add('ixh')
result.add('ixl')
if '(iy' in O:
result.add('iyh')
result.add('iyl')
if i in ['ccf']:
result.add('f')
elif i in {'rra', 'rla', 'rrca', 'rlca'}:
result.add('a')
result.add('f')
elif i in ['xor', 'cp']:
# XOR A, and CP A don't need the a register
if o[0] != 'a':
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
elif i in ['or', 'and']:
# AND A, and OR A do need the a register
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
elif i in {'adc', 'sbc', 'add', 'sub'}:
if len(o) == 1:
if i not in ('sub', 'sbc') or o[0] != 'a':
# sbc a and sub a dont' need the a register
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
else:
if o[0] != o[1] or i in ('add', 'adc'):
# sub HL, HL or sub X, X don't need the X register(s)
result = result.union(single_registers(o))
if i in ['adc', 'sbc']:
result.add('f')
elif i in {'daa', 'rld', 'rrd', 'neg', 'cpl'}:
result.add('a')
elif i in {'rl', 'rr', 'rlc', 'rrc'}:
result = result.union(single_registers(o) + ['f'])
elif i in {'sla', 'sll', 'sra', 'srl', 'inc', 'dec'}:
result = result.union(single_registers(o))
elif i == 'djnz':
result.add('b')
elif i in {'ldir', 'lddr', 'ldi', 'ldd'}:
result = result.union(['b', 'c', 'd', 'e', 'h', 'l'])
elif i in {'cpi', 'cpd', 'cpir', 'cpdr'}:
result = result.union(['a', 'b', 'c', 'h', 'l'])
elif i == 'ld' and not is_number(o[1]):
result = result.union(single_registers(o[1]))
elif i == 'ex':
if o[0] == 'de':
result = result.union(['d', 'e', 'h', 'l'])
elif o[1] == '(sp)':
result = result.union(['h', 'l']) # sp already included
else:
result = result.union(['a', 'f', "a'", "f'"])
elif i == 'exx':
result = result.union(['b', 'c', 'd', 'e', 'h', 'l'])
elif i == 'push':
result = result.union(single_registers(o))
elif i in {'bit', 'set', 'res'}:
result = result.union(single_registers(o[1]))
elif i == 'out':
result.add(o[1])
if o[0] == '(c)':
result.add('c')
elif i == 'in':
if o[1] == '(c)':
result.add('c')
elif i == 'im':
result.add('i')
result = list(result)
return result | python | def requires(self):
""" Returns the registers, operands, etc. required by an instruction.
"""
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
if self.inst == '#pragma':
tmp = self.__instr.split(' ')[1:]
if tmp[0] != 'opt':
return
if tmp[1] == 'require':
return set(flatten_list([single_registers(x.strip(', \t\r')) for x in tmp[2:]]))
return set([])
result = set([])
i = self.inst
o = [x.lower() for x in self.opers]
if i in ['ret', 'pop', 'push']:
result.add('sp')
if self.condition_flag is not None or i in ['sbc', 'adc']:
result.add('f')
for O in o:
if '(hl)' in O:
result.add('h')
result.add('l')
if '(de)' in O:
result.add('d')
result.add('e')
if '(bc)' in O:
result.add('b')
result.add('c')
if '(sp)' in O:
result.add('sp')
if '(ix' in O:
result.add('ixh')
result.add('ixl')
if '(iy' in O:
result.add('iyh')
result.add('iyl')
if i in ['ccf']:
result.add('f')
elif i in {'rra', 'rla', 'rrca', 'rlca'}:
result.add('a')
result.add('f')
elif i in ['xor', 'cp']:
# XOR A, and CP A don't need the a register
if o[0] != 'a':
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
elif i in ['or', 'and']:
# AND A, and OR A do need the a register
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
elif i in {'adc', 'sbc', 'add', 'sub'}:
if len(o) == 1:
if i not in ('sub', 'sbc') or o[0] != 'a':
# sbc a and sub a dont' need the a register
result.add('a')
if o[0][0] != '(' and not is_number(o[0]):
result = result.union(single_registers(o))
else:
if o[0] != o[1] or i in ('add', 'adc'):
# sub HL, HL or sub X, X don't need the X register(s)
result = result.union(single_registers(o))
if i in ['adc', 'sbc']:
result.add('f')
elif i in {'daa', 'rld', 'rrd', 'neg', 'cpl'}:
result.add('a')
elif i in {'rl', 'rr', 'rlc', 'rrc'}:
result = result.union(single_registers(o) + ['f'])
elif i in {'sla', 'sll', 'sra', 'srl', 'inc', 'dec'}:
result = result.union(single_registers(o))
elif i == 'djnz':
result.add('b')
elif i in {'ldir', 'lddr', 'ldi', 'ldd'}:
result = result.union(['b', 'c', 'd', 'e', 'h', 'l'])
elif i in {'cpi', 'cpd', 'cpir', 'cpdr'}:
result = result.union(['a', 'b', 'c', 'h', 'l'])
elif i == 'ld' and not is_number(o[1]):
result = result.union(single_registers(o[1]))
elif i == 'ex':
if o[0] == 'de':
result = result.union(['d', 'e', 'h', 'l'])
elif o[1] == '(sp)':
result = result.union(['h', 'l']) # sp already included
else:
result = result.union(['a', 'f', "a'", "f'"])
elif i == 'exx':
result = result.union(['b', 'c', 'd', 'e', 'h', 'l'])
elif i == 'push':
result = result.union(single_registers(o))
elif i in {'bit', 'set', 'res'}:
result = result.union(single_registers(o[1]))
elif i == 'out':
result.add(o[1])
if o[0] == '(c)':
result.add('c')
elif i == 'in':
if o[1] == '(c)':
result.add('c')
elif i == 'im':
result.add('i')
result = list(result)
return result | Returns the registers, operands, etc. required by an instruction. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1030-L1168 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.affects | def affects(self, reglist):
""" Returns if this instruction affects any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.destroys if x in reglist]) > 0 | python | def affects(self, reglist):
""" Returns if this instruction affects any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.destroys if x in reglist]) > 0 | Returns if this instruction affects any of the registers
in reglist. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1170-L1179 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.needs | def needs(self, reglist):
""" Returns if this instruction need any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.requires if x in reglist]) > 0 | python | def needs(self, reglist):
""" Returns if this instruction need any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.requires if x in reglist]) > 0 | Returns if this instruction need any of the registers
in reglist. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1181-L1190 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.used_labels | def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(), lextab='zxbasmlextab')
tmpLexer.input(tmp)
while True:
token = tmpLexer.token()
if not token:
break
if token.type == 'ID':
result += [token.value]
except:
pass
return result | python | def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(), lextab='zxbasmlextab')
tmpLexer.input(tmp)
while True:
token = tmpLexer.token()
if not token:
break
if token.type == 'ID':
result += [token.value]
except:
pass
return result | Returns a list of required labels for this instruction | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1193-L1216 |
boriel/zxbasic | arch/zx48k/optimizer.py | MemCell.replace_label | def replace_label(self, oldLabel, newLabel):
""" Replaces old label with a new one
"""
if oldLabel == newLabel:
return
tmp = re.compile(r'\b' + oldLabel + r'\b')
last = 0
l = len(newLabel)
while True:
match = tmp.search(self.asm[last:])
if not match:
break
txt = self.asm
self.asm = txt[:last + match.start()] + newLabel + txt[last + match.end():]
last += match.start() + l | python | def replace_label(self, oldLabel, newLabel):
""" Replaces old label with a new one
"""
if oldLabel == newLabel:
return
tmp = re.compile(r'\b' + oldLabel + r'\b')
last = 0
l = len(newLabel)
while True:
match = tmp.search(self.asm[last:])
if not match:
break
txt = self.asm
self.asm = txt[:last + match.start()] + newLabel + txt[last + match.end():]
last += match.start() + l | Replaces old label with a new one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1218-L1234 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.is_partitionable | def is_partitionable(self):
""" Returns if this block can be partitiones in 2 or more blocks,
because if contains enders.
"""
if len(self.mem) < 2:
return False # An atomic block
if any(x.is_ender or x.asm in arch.zx48k.backend.ASMS for x in self.mem):
return True
for label in JUMP_LABELS:
if LABELS[label].basic_block == self and (not self.mem[0].is_label or self.mem[0].inst != label):
return True
return False | python | def is_partitionable(self):
""" Returns if this block can be partitiones in 2 or more blocks,
because if contains enders.
"""
if len(self.mem) < 2:
return False # An atomic block
if any(x.is_ender or x.asm in arch.zx48k.backend.ASMS for x in self.mem):
return True
for label in JUMP_LABELS:
if LABELS[label].basic_block == self and (not self.mem[0].is_label or self.mem[0].inst != label):
return True
return False | Returns if this block can be partitiones in 2 or more blocks,
because if contains enders. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1305-L1319 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.delete_from | def delete_from(self, basic_block):
""" Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
"""
if basic_block is None:
return
if self.lock:
return
self.lock = True
if self.prev is basic_block:
if self.prev.next is self:
self.prev.next = None
self.prev = None
for i in range(len(self.comes_from)):
if self.comes_from[i] is basic_block:
self.comes_from.pop(i)
break
self.lock = False | python | def delete_from(self, basic_block):
""" Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
"""
if basic_block is None:
return
if self.lock:
return
self.lock = True
if self.prev is basic_block:
if self.prev.next is self:
self.prev.next = None
self.prev = None
for i in range(len(self.comes_from)):
if self.comes_from[i] is basic_block:
self.comes_from.pop(i)
break
self.lock = False | Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1327-L1349 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.add_comes_from | def add_comes_from(self, basic_block):
""" This simulates a set. Adds the basic_block to the comes_from
list if not done already.
"""
if basic_block is None:
return
if self.lock:
return
# Return if already added
if basic_block in self.comes_from:
return
self.lock = True
self.comes_from.add(basic_block)
basic_block.add_goes_to(self)
self.lock = False | python | def add_comes_from(self, basic_block):
""" This simulates a set. Adds the basic_block to the comes_from
list if not done already.
"""
if basic_block is None:
return
if self.lock:
return
# Return if already added
if basic_block in self.comes_from:
return
self.lock = True
self.comes_from.add(basic_block)
basic_block.add_goes_to(self)
self.lock = False | This simulates a set. Adds the basic_block to the comes_from
list if not done already. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1376-L1393 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.update_next_block | def update_next_block(self):
""" If the last instruction of this block is a JP, JR or RET (with no
conditions) then the next and goes_to sets just contains a
single block
"""
last = self.mem[-1]
if last.inst not in ('ret', 'jp', 'jr') or last.condition_flag is not None:
return
if last.inst == 'ret':
if self.next is not None:
self.next.delete_from(self)
self.delete_goes(self.next)
return
if last.opers[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % last.opers[0], 2)
LABELS[last.opers[0]] = LabelInfo(last.opers[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
n_block = LABELS[last.opers[0]].basic_block
if self.next is n_block:
return
if self.next.prev == self:
# The next basic block is not this one since it ends with a jump
self.next.delete_from(self)
self.delete_goes(self.next)
self.next = n_block
self.next.add_comes_from(self)
self.add_goes_to(self.next) | python | def update_next_block(self):
""" If the last instruction of this block is a JP, JR or RET (with no
conditions) then the next and goes_to sets just contains a
single block
"""
last = self.mem[-1]
if last.inst not in ('ret', 'jp', 'jr') or last.condition_flag is not None:
return
if last.inst == 'ret':
if self.next is not None:
self.next.delete_from(self)
self.delete_goes(self.next)
return
if last.opers[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % last.opers[0], 2)
LABELS[last.opers[0]] = LabelInfo(last.opers[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
n_block = LABELS[last.opers[0]].basic_block
if self.next is n_block:
return
if self.next.prev == self:
# The next basic block is not this one since it ends with a jump
self.next.delete_from(self)
self.delete_goes(self.next)
self.next = n_block
self.next.add_comes_from(self)
self.add_goes_to(self.next) | If the last instruction of this block is a JP, JR or RET (with no
conditions) then the next and goes_to sets just contains a
single block | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1413-L1443 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.update_goes_and_comes | def update_goes_and_comes(self):
""" Once the block is a Basic one, check the last instruction and updates
goes_to and comes_from set of the receivers.
Note: jp, jr and ret are already done in update_next_block()
"""
# Remove any block from the comes_from and goes_to list except the PREVIOUS and NEXT
if not len(self):
return
if self.mem[-1].inst == 'ret':
return # subroutine returns are updated from CALLer blocks
self.update_used_by_list()
if not self.mem[-1].is_ender:
return
last = self.mem[-1]
inst = last.inst
oper = last.opers
cond = last.condition_flag
if oper and oper[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % oper[0], 1)
LABELS[oper[0]] = LabelInfo(oper[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
if inst == 'djnz' or inst in ('jp', 'jr') and cond is not None:
if oper[0] in LABELS.keys():
self.add_goes_to(LABELS[oper[0]].basic_block)
elif inst in ('jp', 'jr') and cond is None:
if oper[0] in LABELS.keys():
self.delete_goes(self.next)
self.next = LABELS[oper[0]].basic_block
self.add_goes_to(self.next)
elif inst == 'call':
LABELS[oper[0]].basic_block.add_comes_from(self)
stack = [LABELS[oper[0]].basic_block]
bbset = IdentitySet()
while stack:
bb = stack.pop(0)
while bb is not None:
if bb in bbset:
break
bbset.add(bb)
if len(bb):
bb1 = bb[-1]
if bb1.inst == 'ret':
bb.add_goes_to(self.next)
if bb1.condition_flag is None: # 'ret'
break
if bb1.inst in ('jp', 'jr') and bb1.condition_flag is not None: # jp/jr nc/nz/.. LABEL
if bb1.opers[0] in LABELS: # some labels does not exist (e.g. immediate numeric addresses)
stack += [LABELS[bb1.opers[0]].basic_block]
bb = bb.next # next contiguous block
if cond is None:
self.calls.add(LABELS[oper[0]].basic_block) | python | def update_goes_and_comes(self):
""" Once the block is a Basic one, check the last instruction and updates
goes_to and comes_from set of the receivers.
Note: jp, jr and ret are already done in update_next_block()
"""
# Remove any block from the comes_from and goes_to list except the PREVIOUS and NEXT
if not len(self):
return
if self.mem[-1].inst == 'ret':
return # subroutine returns are updated from CALLer blocks
self.update_used_by_list()
if not self.mem[-1].is_ender:
return
last = self.mem[-1]
inst = last.inst
oper = last.opers
cond = last.condition_flag
if oper and oper[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % oper[0], 1)
LABELS[oper[0]] = LabelInfo(oper[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
if inst == 'djnz' or inst in ('jp', 'jr') and cond is not None:
if oper[0] in LABELS.keys():
self.add_goes_to(LABELS[oper[0]].basic_block)
elif inst in ('jp', 'jr') and cond is None:
if oper[0] in LABELS.keys():
self.delete_goes(self.next)
self.next = LABELS[oper[0]].basic_block
self.add_goes_to(self.next)
elif inst == 'call':
LABELS[oper[0]].basic_block.add_comes_from(self)
stack = [LABELS[oper[0]].basic_block]
bbset = IdentitySet()
while stack:
bb = stack.pop(0)
while bb is not None:
if bb in bbset:
break
bbset.add(bb)
if len(bb):
bb1 = bb[-1]
if bb1.inst == 'ret':
bb.add_goes_to(self.next)
if bb1.condition_flag is None: # 'ret'
break
if bb1.inst in ('jp', 'jr') and bb1.condition_flag is not None: # jp/jr nc/nz/.. LABEL
if bb1.opers[0] in LABELS: # some labels does not exist (e.g. immediate numeric addresses)
stack += [LABELS[bb1.opers[0]].basic_block]
bb = bb.next # next contiguous block
if cond is None:
self.calls.add(LABELS[oper[0]].basic_block) | Once the block is a Basic one, check the last instruction and updates
goes_to and comes_from set of the receivers.
Note: jp, jr and ret are already done in update_next_block() | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1466-L1529 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.is_used | def is_used(self, regs, i, top=None):
""" Checks whether any of the given regs are required from the given point
to the end or not.
"""
if i < 0:
i = 0
if self.lock:
return True
regs = list(regs) # make a copy
if top is None:
top = len(self)
else:
top -= 1
for ii in range(i, top):
for r in self.mem[ii].requires:
if r in regs:
return True
for r in self.mem[ii].destroys:
if r in regs:
regs.remove(r)
if not regs:
return False
self.lock = True
result = self.goes_requires(regs)
self.lock = False
return result | python | def is_used(self, regs, i, top=None):
""" Checks whether any of the given regs are required from the given point
to the end or not.
"""
if i < 0:
i = 0
if self.lock:
return True
regs = list(regs) # make a copy
if top is None:
top = len(self)
else:
top -= 1
for ii in range(i, top):
for r in self.mem[ii].requires:
if r in regs:
return True
for r in self.mem[ii].destroys:
if r in regs:
regs.remove(r)
if not regs:
return False
self.lock = True
result = self.goes_requires(regs)
self.lock = False
return result | Checks whether any of the given regs are required from the given point
to the end or not. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1531-L1563 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.safe_to_write | def safe_to_write(self, regs, i=0, end_=0):
""" Given a list of registers (8 or 16 bits) returns a list of them
that are safe to modify from the given index until the position given
which, if omitted, defaults to the end of the block.
:param regs: register or iterable of registers (8 or 16 bit one)
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
"""
if is_register(regs):
regs = set(single_registers(regs))
else:
regs = set(single_registers(x) for x in regs)
return not regs.intersection(self.requires(i, end_)) | python | def safe_to_write(self, regs, i=0, end_=0):
""" Given a list of registers (8 or 16 bits) returns a list of them
that are safe to modify from the given index until the position given
which, if omitted, defaults to the end of the block.
:param regs: register or iterable of registers (8 or 16 bit one)
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
"""
if is_register(regs):
regs = set(single_registers(regs))
else:
regs = set(single_registers(x) for x in regs)
return not regs.intersection(self.requires(i, end_)) | Given a list of registers (8 or 16 bits) returns a list of them
that are safe to modify from the given index until the position given
which, if omitted, defaults to the end of the block.
:param regs: register or iterable of registers (8 or 16 bit one)
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1565-L1578 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.requires | def requires(self, i=0, end_=None):
""" Returns a list of registers and variables this block requires.
By default checks from the beginning (i = 0).
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
"""
if i < 0:
i = 0
end_ = len(self) if end_ is None or end_ > len(self) else end_
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
result = []
for ii in range(i, end_):
for r in self.mem[ii].requires:
r = r.lower()
if r in regs:
result.append(r)
regs.remove(r)
for r in self.mem[ii].destroys:
r = r.lower()
if r in regs:
regs.remove(r)
if not regs:
break
return result | python | def requires(self, i=0, end_=None):
""" Returns a list of registers and variables this block requires.
By default checks from the beginning (i = 0).
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
"""
if i < 0:
i = 0
end_ = len(self) if end_ is None or end_ > len(self) else end_
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
result = []
for ii in range(i, end_):
for r in self.mem[ii].requires:
r = r.lower()
if r in regs:
result.append(r)
regs.remove(r)
for r in self.mem[ii].destroys:
r = r.lower()
if r in regs:
regs.remove(r)
if not regs:
break
return result | Returns a list of registers and variables this block requires.
By default checks from the beginning (i = 0).
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1580-L1608 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.destroys | def destroys(self, i=0):
""" Returns a list of registers this block destroys
By default checks from the beginning (i = 0).
"""
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
top = len(self)
result = []
for ii in range(i, top):
for r in self.mem[ii].destroys:
if r in regs:
result.append(r)
regs.remove(r)
if not regs:
break
return result | python | def destroys(self, i=0):
""" Returns a list of registers this block destroys
By default checks from the beginning (i = 0).
"""
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
top = len(self)
result = []
for ii in range(i, top):
for r in self.mem[ii].destroys:
if r in regs:
result.append(r)
regs.remove(r)
if not regs:
break
return result | Returns a list of registers this block destroys
By default checks from the beginning (i = 0). | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1610-L1627 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.swap | def swap(self, a, b):
""" Swaps mem positions a and b
"""
self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
self.asm[a], self.asm[b] = self.asm[b], self.asm[a] | python | def swap(self, a, b):
""" Swaps mem positions a and b
"""
self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
self.asm[a], self.asm[b] = self.asm[b], self.asm[a] | Swaps mem positions a and b | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1629-L1633 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.goes_requires | def goes_requires(self, regs):
""" Returns whether any of the goes_to block requires any of
the given registers.
"""
if len(self) and self.mem[-1].inst == 'call' and self.mem[-1].condition_flag is None:
for block in self.calls:
if block.is_used(regs, 0):
return True
d = block.destroys()
if not len([x for x in regs if x not in d]):
return False # If all registers are destroyed then they're not used
for block in self.goes_to:
if block.is_used(regs, 0):
return True
return False | python | def goes_requires(self, regs):
""" Returns whether any of the goes_to block requires any of
the given registers.
"""
if len(self) and self.mem[-1].inst == 'call' and self.mem[-1].condition_flag is None:
for block in self.calls:
if block.is_used(regs, 0):
return True
d = block.destroys()
if not len([x for x in regs if x not in d]):
return False # If all registers are destroyed then they're not used
for block in self.goes_to:
if block.is_used(regs, 0):
return True
return False | Returns whether any of the goes_to block requires any of
the given registers. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1635-L1652 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.get_label_idx | def get_label_idx(self, label):
""" Returns the index of a label.
Returns None if not found.
"""
for i in range(len(self)):
if self.mem[i].is_label and self.mem[i].inst == label:
return i
return None | python | def get_label_idx(self, label):
""" Returns the index of a label.
Returns None if not found.
"""
for i in range(len(self)):
if self.mem[i].is_label and self.mem[i].inst == label:
return i
return None | Returns the index of a label.
Returns None if not found. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1654-L1662 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.get_first_non_label_instruction | def get_first_non_label_instruction(self):
""" Returns the memcell of the given block, which is
not a LABEL.
"""
for i in range(len(self)):
if not self.mem[i].is_label:
return self.mem[i]
return None | python | def get_first_non_label_instruction(self):
""" Returns the memcell of the given block, which is
not a LABEL.
"""
for i in range(len(self)):
if not self.mem[i].is_label:
return self.mem[i]
return None | Returns the memcell of the given block, which is
not a LABEL. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1664-L1672 |
boriel/zxbasic | arch/zx48k/optimizer.py | BasicBlock.optimize | def optimize(self):
""" Tries to detect peep-hole patterns in this basic block
and remove them.
"""
changed = OPTIONS.optimization.value > 2 # only with -O3 will enter here
while changed:
changed = False
regs = Registers()
if len(self) and self[-1].inst in ('jp', 'jr') and \
self.original_next is LABELS[self[-1].opers[0]].basic_block:
# { jp Label ; Label: ; ... } => { Label: ; ... }
LABELS[self[-1].opers[0]].used_by.remove(self)
self.pop(len(self) - 1)
changed = True
continue
for i in range(len(self)):
try:
if self.mem[i].is_label:
# ignore labels
continue
except IndexError:
print(i)
print('\n'.join(str(x) for x in self.mem))
raise
i1 = self.mem[i].inst
o1 = self.mem[i].opers
if i > 0:
i0 = self.mem[i - 1].inst
o0 = self.mem[i - 1].opers
else:
i0 = o0 = None
if i < len(self) - 1:
i2 = self.mem[i + 1].inst
o2 = self.mem[i + 1].opers
else:
i2 = o2 = None
if i < len(self) - 2:
i3 = self.mem[i + 2].inst
o3 = self.mem[i + 2].opers
else:
i3 = o3 = None
if i1 == 'ld':
if OPT00 and o1[0] == o1[1]:
# { LD X, X } => {}
self.pop(i)
changed = True
break
if OPT01 and o0 == 'ld' and o0[0] == o1[1] and o1[0] == o0[1]:
# { LD A, X; LD X, A} => {LD A, X}
self.pop(i)
changed = True
break
if OPT02 and i0 == i1 == 'ld' and o0[1] == o1[1] and \
is_register(o0[0]) and is_register(o1[0]) and not is_16bit_idx_register(o1[0]):
if is_8bit_register(o1[0]):
if not is_8bit_register(o1[1]):
# { LD r1, N; LD r2, N} => {LD r1, N; LD r2, r1}
changed = True
self[i] = 'ld %s, %s' % (o1[0], o0[0])
break
else:
changed = True
# {LD r1, NN; LD r2, NN} => { LD r1, NN; LD r2H, r1H; LD r2L, r1L}
self[i] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self.insert(i + 1, 'ld %s, %s' % (LO16(o1[0]), LO16(o0[0])))
break
if OPT03 and is_register(o1[0]) and o1[0] != 'sp' and \
not self.is_used(single_registers(o1[0]), i + 1):
# LD X, nnn ; X not used later => Remove instruction
tmp = str(self.asm)
self.pop(i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT04 and o1 == ['h', 'a'] and i2 == 'ld' and o2[0] == 'a' \
and i3 == 'sub' and o3[0] == 'h' and not self.is_used('h', i + 3):
if is_number(o2[1]):
self[i] = 'neg'
self[i + 1] = 'add a, %s' % o2[1]
self[i + 2] = 'ccf'
changed = True
break
if OPT05 and regs._is(o1[0], o1[1]): # and regs.get(o1[0])[0:3] != '(ix':
tmp = str(self.asm)
self.pop(i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT06 and o1[0] in ('hl', 'de') and \
i2 == 'ex' and o2[0] == 'de' and o2[1] == 'hl' and \
not self.is_used(single_registers(o1[0]), i + 2):
# { LD HL, XX ; EX DE, HL; POP HL } ::= { LD DE, XX ; POP HL }
reg = 'de' if o1[0] == 'hl' else 'hl'
self.pop(i + 1)
self[i] = 'ld %s, %s' % (reg, o1[1])
changed = True
break
if OPT07 and i0 == 'ld' and i2 == 'ld' and o2[1] == 'hl' and not self.is_used(['h', 'l'], i + 2) \
and (o0[0] == 'h' and o0[1] == 'b' and o1[0] == 'l' and o1[1] == 'c' or
o0[0] == 'l' and o0[1] == 'c' and o1[0] == 'h' and o1[1] == 'b' or
o0[0] == 'h' and o0[1] == 'd' and o1[0] == 'l' and o1[1] == 'e' or
o0[0] == 'l' and o0[1] == 'e' and o1[0] == 'h' and o1[1] == 'd'):
# { LD h, rH ; LD l, rl ; LD (XX), HL } ::= { LD (XX), R }
tmp = str(self.asm)
r2 = 'de' if o0[1] in ('d', 'e') else 'bc'
self[i + 1] = 'ld %s, %s' % (o2[0], r2)
self.pop(i)
self.pop(i - 1)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT08 and i1 == i2 == 'ld' and i > 0 and \
(o1[1] == 'h' and o1[0] == 'b' and o2[1] == 'l' and o2[0] == 'c' or
o1[1] == 'l' and o1[0] == 'c' and o2[1] == 'h' and o2[0] == 'b' or
o1[1] == 'h' and o1[0] == 'd' and o2[1] == 'l' and o2[0] == 'e' or
o1[1] == 'l' and o1[0] == 'e' and o2[1] == 'h' and o2[
0] == 'd') and \
regs.get('hl') is not None and not self.is_used(['h', 'l'], i + 2) and \
not self[i - 1].needs(['h', 'l']) and not self[i - 1].affects(['h', 'l']):
# { LD HL, XXX ; <inst> ; LD rH, H; LD rL, L } ::= { LD HL, XXX ; LD rH, H; LD rL, L; <inst> }
changed = True
tmp = str(self.asm)
self.swap(i - 1, i + 1)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT09 and i > 0 and i0 == i1 == i2 == 'ld' and \
o0[0] == 'hl' and \
(o1[1] == 'h' and o1[0] == 'b' and o2[1] == 'l' and o2[0] == 'c' or
o1[1] == 'l' and o1[0] == 'c' and o2[1] == 'h' and o2[0] == 'b' or
o1[1] == 'h' and o1[0] == 'd' and o2[1] == 'l' and o2[0] == 'e' or
o1[1] == 'l' and o1[0] == 'e' and o2[1] == 'h' and o2[0] == 'd') and \
not self.is_used(['h', 'l'], i + 2):
# { LD HL, XXX ; LD rH, H; LD rL, L } ::= { LD rr, XXX }
changed = True
r1 = 'de' if o1[0] in ('d', 'e') else 'bc'
tmp = str(self.asm)
self[i - 1] = 'ld %s, %s' % (r1, o0[1])
self.pop(i + 1)
self.pop(i)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT10 and i1 in ('inc', 'dec') and o1[0] == 'a':
if i2 == i0 == 'ld' and o2[0] == o0[1] and 'a' == o0[0] == o2[1] and o0[1][0] == '(':
if not RE_INDIR.match(o2[0]):
if not self.is_used(['a', 'h', 'l'], i + 2):
# { LD A, (X); [ DEC A | INC A ]; LD (X), A} ::= {LD HL, X; [ DEC (HL) | INC (HL) ]}
tmp = str(self.asm)
self.pop(i + 1)
self[i - 1] = 'ld hl, %s' % (o0[1][1:-1])
self[i] = '%s (hl)' % i1
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
else:
if not self.is_used(['a'], i + 2):
# { LD A, (IX + n); [ DEC A | INC A ]; LD (X), A} ::=
# { [ DEC (IX + n) | INC (IX + n) ] }
tmp = str(self.asm)
self.pop(i + 1)
self.pop(i)
self[i - 1] = '%s %s' % (i1, o0[1])
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT11 and i0 == 'push' and i3 == 'pop' and o0[0] != o3[0] \
and o0[0] in ('hl', 'de') and o3[0] in ('hl', 'de') \
and i1 == i2 == 'ld' and (
o1[0] == HI16(o0[0]) and o2[0] == LO16(o0[0]) and o1[1] == HI16(o3[0]) and
o2[1] == LO16(o3[0]) or
o2[0] == HI16(o0[0]) and o1[0] == LO16(o0[0]) and o2[1] == HI16(
o3[0]) and o1[1] == LO16(o3[0])):
# { PUSH HL; LD H, D; LD L, E; POP HL } ::= {EX DE, HL}
self.pop(i + 2)
self.pop(i + 1)
self.pop(i)
self[i - 1] = 'ex de, hl'
changed = True
break
if i0 == 'push' and i1 == 'pop':
if OPT12 and o0[0] == o1[0]:
# { PUSH X ; POP X } ::= { }
self.pop(i)
self.pop(i - 1)
changed = True
break
if OPT13 and o0[0] in ('de', 'hl') and o1[0] in ('de', 'hl') and not self.is_used(
single_registers(o0[0]), i + 1):
# { PUSH DE ; POP HL } ::= { EX DE, HL }
self.pop(i)
self[i - 1] = 'ex de, hl'
changed = True
break
if OPT14 and 'af' in (o0[0], o1[0]):
# { push Xx ; pop af } => { ld a, X }
if not self.is_used(o1[0][1], i + 1):
self[i - 1] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self.pop(i)
changed = True
break
elif OPT15 and not is_16bit_idx_register(o0[0]) and not is_16bit_idx_register(
o1[0]) and 'af' not in (o0[0], o1[0]):
# { push Xx ; pop Yy } => { ld Y, X ; ld y, x }
self[i - 1] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self[i] = 'ld %s, %s' % (LO16(o1[0]), LO16(o0[0]))
changed = True
break
if OPT16 and i > 0 and not self.mem[i - 1].is_label and i1 == 'pop' and \
(not self.mem[i - 1].affects([o1[0], 'sp']) or
self.safe_to_write(o1[0], i + 1)) and \
not self.mem[i - 1].needs([o1[0], 'sp']):
# { <inst>; POP X } => { POP X; <inst> } ; if inst does not uses X
tmp = str(self.asm)
self.swap(i - 1, i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT17 and i1 == 'xor' and o1[0] == 'a' and regs._is('a', 0) and regs.Z and not regs.C:
tmp = str(self.asm)
self.pop(i)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
changed = True
break
if OPT18 and i3 is not None and \
(i0 == i1 == 'ld' and i2 == i3 == 'push') and \
(o0[0] == o3[0] == 'de' and o1[0] == o2[0] == 'bc'): # and \
if not self.is_used(['h', 'l', 'd', 'e', 'b', 'c'], i + 3):
# { LD DE, (X2) ; LD BC, (X1); PUSH DE; PUSH BC } ::=
# { LD HL, (X2); PUSH HL; LD HL, (X1); PUSH HL }
self[i - 1] = 'ld hl, %s' % o1[1]
self[i] = 'push hl'
self[i + 1] = 'ld hl, %s' % o0[1]
self[i + 2] = 'push hl'
changed = True
break
if i1 in ('jp', 'jr', 'call') and o1[0] in JUMP_LABELS:
c = self.mem[i].condition_flag
if OPT19 and c is not None:
if c == 'c' and regs.C == 1 or \
c == 'z' and regs.Z == 1 or \
c == 'nc' and regs.C == 0 or \
c == 'nz' and regs.Z == 0:
# If the condition is always satisfied, replace with a simple jump / call
changed = True
tmp = str(self.asm)
self[i] = '%s %s' % (i1, o1[0])
self.update_goes_and_comes()
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
ii = LABELS[o1[0]].basic_block.get_first_non_label_instruction()
ii1 = None if ii is None else ii.inst
cc = None if ii is None else ii.condition_flag
# Are we calling / jumping into another jump?
if OPT20 and ii1 in ('jp', 'jr') and (
cc is None or
cc == c or
cc == 'c' and regs.C == 1 or
cc == 'z' and regs.Z == 1 or
cc == 'nc' and regs.C == 0 or
cc == 'nz' and regs.Z == 0):
if c is None:
c = ''
else:
c = c + ', '
changed = True
tmp = str(self.asm)
LABELS[o1[0]].used_by.remove(self) # This block no longer uses this label
self[i] = '%s %s%s' % (i1, c, ii.opers[0])
self.update_goes_and_comes()
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT22 and i0 == 'sbc' and o0[0] == o0[1] == 'a' and \
i1 == 'or' and o1[0] == 'a' and \
i2 == 'jp' and \
self[i + 1].condition_flag is not None and \
not self.is_used(['a'], i + 2):
c = self.mem[i + 1].condition_flag
if c in ('z', 'nz'):
c = 'c' if c == 'nz' else 'nc'
changed = True
self[i + 1] = 'jp %s, %s' % (c, o2[0])
self.pop(i)
self.pop(i - 1)
break
if OPT23 and i0 == 'ld' and is_16bit_register(o0[0]) and o0[1][0] == '(' and \
i1 == 'ld' and o1[0] == 'a' and o1[1] == LO16(o0[0]) and not self.is_used(
single_registers(o0[0]), i + 1):
# { LD HL, (X) ; LD A, L } ::= { LD A, (X) }
self.pop(i)
self[i - 1] = 'ld a, %s' % o0[1]
changed = True
break
if OPT24 and i1 == i2 == 'ccf': # { ccf ; ccf } ::= { }
self.pop(i)
self.pop(i)
changed = True
break
if OPT25 and i1 == 'ld' and is_register(o1[0]) and o1[0] != 'sp':
is8 = is_8bit_register(o1[0])
ss = [x for x, y in regs.regs.items() if x != o1[0] and y is not None and y == regs.get(o1[1]) and
not is_8bit_register(o1[1])]
for r_ in ss:
if is8 != is_8bit_register(r_):
continue
changed = True
if is8: # ld A, n; ld B, n => ld A, n; ld B, A
self[i] = 'ld %s, %s' % (o1[0], r_)
else: # ld HL, n; ld DE, n => ld HL, n; ld d, h; ld e, l
# 16 bit register
self[i] = 'ld %s, %s' % (HI16(o1[0]), HI16(r_))
self.insert(i + 1, 'ld %s, %s' % (LO16(o1[0]), LO16(r_)))
break
if changed:
break
if OPT26 and i1 == i2 == 'ld' and (o1[0], o1[1], o2[0], o2[1]) == ('d', 'h', 'e', 'l') and \
not self.is_used(['h', 'l'], i + 2):
self[i] = 'ex de, hl'
self.pop(i + 1)
changed = True
break
if OPT27 and i1 in ('cp', 'or', 'and', 'add', 'adc', 'sub', 'sbc') and o1[-1] != 'a' and \
not self.is_used(o1[-1], i + 1) and i0 == 'ld' and o0[0] == o1[-1] and \
(o0[1] == '(hl)' or RE_IXIND.match(o0[1])):
template = '{0} %s{1}' % ('a, ' if i1 in ('add', 'adc', 'sbc') else '')
self[i] = template.format(i1, o0[1])
self.pop(i - 1)
changed = True
break
regs.op(i1, o1) | python | def optimize(self):
""" Tries to detect peep-hole patterns in this basic block
and remove them.
"""
changed = OPTIONS.optimization.value > 2 # only with -O3 will enter here
while changed:
changed = False
regs = Registers()
if len(self) and self[-1].inst in ('jp', 'jr') and \
self.original_next is LABELS[self[-1].opers[0]].basic_block:
# { jp Label ; Label: ; ... } => { Label: ; ... }
LABELS[self[-1].opers[0]].used_by.remove(self)
self.pop(len(self) - 1)
changed = True
continue
for i in range(len(self)):
try:
if self.mem[i].is_label:
# ignore labels
continue
except IndexError:
print(i)
print('\n'.join(str(x) for x in self.mem))
raise
i1 = self.mem[i].inst
o1 = self.mem[i].opers
if i > 0:
i0 = self.mem[i - 1].inst
o0 = self.mem[i - 1].opers
else:
i0 = o0 = None
if i < len(self) - 1:
i2 = self.mem[i + 1].inst
o2 = self.mem[i + 1].opers
else:
i2 = o2 = None
if i < len(self) - 2:
i3 = self.mem[i + 2].inst
o3 = self.mem[i + 2].opers
else:
i3 = o3 = None
if i1 == 'ld':
if OPT00 and o1[0] == o1[1]:
# { LD X, X } => {}
self.pop(i)
changed = True
break
if OPT01 and o0 == 'ld' and o0[0] == o1[1] and o1[0] == o0[1]:
# { LD A, X; LD X, A} => {LD A, X}
self.pop(i)
changed = True
break
if OPT02 and i0 == i1 == 'ld' and o0[1] == o1[1] and \
is_register(o0[0]) and is_register(o1[0]) and not is_16bit_idx_register(o1[0]):
if is_8bit_register(o1[0]):
if not is_8bit_register(o1[1]):
# { LD r1, N; LD r2, N} => {LD r1, N; LD r2, r1}
changed = True
self[i] = 'ld %s, %s' % (o1[0], o0[0])
break
else:
changed = True
# {LD r1, NN; LD r2, NN} => { LD r1, NN; LD r2H, r1H; LD r2L, r1L}
self[i] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self.insert(i + 1, 'ld %s, %s' % (LO16(o1[0]), LO16(o0[0])))
break
if OPT03 and is_register(o1[0]) and o1[0] != 'sp' and \
not self.is_used(single_registers(o1[0]), i + 1):
# LD X, nnn ; X not used later => Remove instruction
tmp = str(self.asm)
self.pop(i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT04 and o1 == ['h', 'a'] and i2 == 'ld' and o2[0] == 'a' \
and i3 == 'sub' and o3[0] == 'h' and not self.is_used('h', i + 3):
if is_number(o2[1]):
self[i] = 'neg'
self[i + 1] = 'add a, %s' % o2[1]
self[i + 2] = 'ccf'
changed = True
break
if OPT05 and regs._is(o1[0], o1[1]): # and regs.get(o1[0])[0:3] != '(ix':
tmp = str(self.asm)
self.pop(i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT06 and o1[0] in ('hl', 'de') and \
i2 == 'ex' and o2[0] == 'de' and o2[1] == 'hl' and \
not self.is_used(single_registers(o1[0]), i + 2):
# { LD HL, XX ; EX DE, HL; POP HL } ::= { LD DE, XX ; POP HL }
reg = 'de' if o1[0] == 'hl' else 'hl'
self.pop(i + 1)
self[i] = 'ld %s, %s' % (reg, o1[1])
changed = True
break
if OPT07 and i0 == 'ld' and i2 == 'ld' and o2[1] == 'hl' and not self.is_used(['h', 'l'], i + 2) \
and (o0[0] == 'h' and o0[1] == 'b' and o1[0] == 'l' and o1[1] == 'c' or
o0[0] == 'l' and o0[1] == 'c' and o1[0] == 'h' and o1[1] == 'b' or
o0[0] == 'h' and o0[1] == 'd' and o1[0] == 'l' and o1[1] == 'e' or
o0[0] == 'l' and o0[1] == 'e' and o1[0] == 'h' and o1[1] == 'd'):
# { LD h, rH ; LD l, rl ; LD (XX), HL } ::= { LD (XX), R }
tmp = str(self.asm)
r2 = 'de' if o0[1] in ('d', 'e') else 'bc'
self[i + 1] = 'ld %s, %s' % (o2[0], r2)
self.pop(i)
self.pop(i - 1)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT08 and i1 == i2 == 'ld' and i > 0 and \
(o1[1] == 'h' and o1[0] == 'b' and o2[1] == 'l' and o2[0] == 'c' or
o1[1] == 'l' and o1[0] == 'c' and o2[1] == 'h' and o2[0] == 'b' or
o1[1] == 'h' and o1[0] == 'd' and o2[1] == 'l' and o2[0] == 'e' or
o1[1] == 'l' and o1[0] == 'e' and o2[1] == 'h' and o2[
0] == 'd') and \
regs.get('hl') is not None and not self.is_used(['h', 'l'], i + 2) and \
not self[i - 1].needs(['h', 'l']) and not self[i - 1].affects(['h', 'l']):
# { LD HL, XXX ; <inst> ; LD rH, H; LD rL, L } ::= { LD HL, XXX ; LD rH, H; LD rL, L; <inst> }
changed = True
tmp = str(self.asm)
self.swap(i - 1, i + 1)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT09 and i > 0 and i0 == i1 == i2 == 'ld' and \
o0[0] == 'hl' and \
(o1[1] == 'h' and o1[0] == 'b' and o2[1] == 'l' and o2[0] == 'c' or
o1[1] == 'l' and o1[0] == 'c' and o2[1] == 'h' and o2[0] == 'b' or
o1[1] == 'h' and o1[0] == 'd' and o2[1] == 'l' and o2[0] == 'e' or
o1[1] == 'l' and o1[0] == 'e' and o2[1] == 'h' and o2[0] == 'd') and \
not self.is_used(['h', 'l'], i + 2):
# { LD HL, XXX ; LD rH, H; LD rL, L } ::= { LD rr, XXX }
changed = True
r1 = 'de' if o1[0] in ('d', 'e') else 'bc'
tmp = str(self.asm)
self[i - 1] = 'ld %s, %s' % (r1, o0[1])
self.pop(i + 1)
self.pop(i)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT10 and i1 in ('inc', 'dec') and o1[0] == 'a':
if i2 == i0 == 'ld' and o2[0] == o0[1] and 'a' == o0[0] == o2[1] and o0[1][0] == '(':
if not RE_INDIR.match(o2[0]):
if not self.is_used(['a', 'h', 'l'], i + 2):
# { LD A, (X); [ DEC A | INC A ]; LD (X), A} ::= {LD HL, X; [ DEC (HL) | INC (HL) ]}
tmp = str(self.asm)
self.pop(i + 1)
self[i - 1] = 'ld hl, %s' % (o0[1][1:-1])
self[i] = '%s (hl)' % i1
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
else:
if not self.is_used(['a'], i + 2):
# { LD A, (IX + n); [ DEC A | INC A ]; LD (X), A} ::=
# { [ DEC (IX + n) | INC (IX + n) ] }
tmp = str(self.asm)
self.pop(i + 1)
self.pop(i)
self[i - 1] = '%s %s' % (i1, o0[1])
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT11 and i0 == 'push' and i3 == 'pop' and o0[0] != o3[0] \
and o0[0] in ('hl', 'de') and o3[0] in ('hl', 'de') \
and i1 == i2 == 'ld' and (
o1[0] == HI16(o0[0]) and o2[0] == LO16(o0[0]) and o1[1] == HI16(o3[0]) and
o2[1] == LO16(o3[0]) or
o2[0] == HI16(o0[0]) and o1[0] == LO16(o0[0]) and o2[1] == HI16(
o3[0]) and o1[1] == LO16(o3[0])):
# { PUSH HL; LD H, D; LD L, E; POP HL } ::= {EX DE, HL}
self.pop(i + 2)
self.pop(i + 1)
self.pop(i)
self[i - 1] = 'ex de, hl'
changed = True
break
if i0 == 'push' and i1 == 'pop':
if OPT12 and o0[0] == o1[0]:
# { PUSH X ; POP X } ::= { }
self.pop(i)
self.pop(i - 1)
changed = True
break
if OPT13 and o0[0] in ('de', 'hl') and o1[0] in ('de', 'hl') and not self.is_used(
single_registers(o0[0]), i + 1):
# { PUSH DE ; POP HL } ::= { EX DE, HL }
self.pop(i)
self[i - 1] = 'ex de, hl'
changed = True
break
if OPT14 and 'af' in (o0[0], o1[0]):
# { push Xx ; pop af } => { ld a, X }
if not self.is_used(o1[0][1], i + 1):
self[i - 1] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self.pop(i)
changed = True
break
elif OPT15 and not is_16bit_idx_register(o0[0]) and not is_16bit_idx_register(
o1[0]) and 'af' not in (o0[0], o1[0]):
# { push Xx ; pop Yy } => { ld Y, X ; ld y, x }
self[i - 1] = 'ld %s, %s' % (HI16(o1[0]), HI16(o0[0]))
self[i] = 'ld %s, %s' % (LO16(o1[0]), LO16(o0[0]))
changed = True
break
if OPT16 and i > 0 and not self.mem[i - 1].is_label and i1 == 'pop' and \
(not self.mem[i - 1].affects([o1[0], 'sp']) or
self.safe_to_write(o1[0], i + 1)) and \
not self.mem[i - 1].needs([o1[0], 'sp']):
# { <inst>; POP X } => { POP X; <inst> } ; if inst does not uses X
tmp = str(self.asm)
self.swap(i - 1, i)
changed = True
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT17 and i1 == 'xor' and o1[0] == 'a' and regs._is('a', 0) and regs.Z and not regs.C:
tmp = str(self.asm)
self.pop(i)
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
changed = True
break
if OPT18 and i3 is not None and \
(i0 == i1 == 'ld' and i2 == i3 == 'push') and \
(o0[0] == o3[0] == 'de' and o1[0] == o2[0] == 'bc'): # and \
if not self.is_used(['h', 'l', 'd', 'e', 'b', 'c'], i + 3):
# { LD DE, (X2) ; LD BC, (X1); PUSH DE; PUSH BC } ::=
# { LD HL, (X2); PUSH HL; LD HL, (X1); PUSH HL }
self[i - 1] = 'ld hl, %s' % o1[1]
self[i] = 'push hl'
self[i + 1] = 'ld hl, %s' % o0[1]
self[i + 2] = 'push hl'
changed = True
break
if i1 in ('jp', 'jr', 'call') and o1[0] in JUMP_LABELS:
c = self.mem[i].condition_flag
if OPT19 and c is not None:
if c == 'c' and regs.C == 1 or \
c == 'z' and regs.Z == 1 or \
c == 'nc' and regs.C == 0 or \
c == 'nz' and regs.Z == 0:
# If the condition is always satisfied, replace with a simple jump / call
changed = True
tmp = str(self.asm)
self[i] = '%s %s' % (i1, o1[0])
self.update_goes_and_comes()
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
ii = LABELS[o1[0]].basic_block.get_first_non_label_instruction()
ii1 = None if ii is None else ii.inst
cc = None if ii is None else ii.condition_flag
# Are we calling / jumping into another jump?
if OPT20 and ii1 in ('jp', 'jr') and (
cc is None or
cc == c or
cc == 'c' and regs.C == 1 or
cc == 'z' and regs.Z == 1 or
cc == 'nc' and regs.C == 0 or
cc == 'nz' and regs.Z == 0):
if c is None:
c = ''
else:
c = c + ', '
changed = True
tmp = str(self.asm)
LABELS[o1[0]].used_by.remove(self) # This block no longer uses this label
self[i] = '%s %s%s' % (i1, c, ii.opers[0])
self.update_goes_and_comes()
__DEBUG__('Changed %s ==> %s' % (tmp, self.asm), 2)
break
if OPT22 and i0 == 'sbc' and o0[0] == o0[1] == 'a' and \
i1 == 'or' and o1[0] == 'a' and \
i2 == 'jp' and \
self[i + 1].condition_flag is not None and \
not self.is_used(['a'], i + 2):
c = self.mem[i + 1].condition_flag
if c in ('z', 'nz'):
c = 'c' if c == 'nz' else 'nc'
changed = True
self[i + 1] = 'jp %s, %s' % (c, o2[0])
self.pop(i)
self.pop(i - 1)
break
if OPT23 and i0 == 'ld' and is_16bit_register(o0[0]) and o0[1][0] == '(' and \
i1 == 'ld' and o1[0] == 'a' and o1[1] == LO16(o0[0]) and not self.is_used(
single_registers(o0[0]), i + 1):
# { LD HL, (X) ; LD A, L } ::= { LD A, (X) }
self.pop(i)
self[i - 1] = 'ld a, %s' % o0[1]
changed = True
break
if OPT24 and i1 == i2 == 'ccf': # { ccf ; ccf } ::= { }
self.pop(i)
self.pop(i)
changed = True
break
if OPT25 and i1 == 'ld' and is_register(o1[0]) and o1[0] != 'sp':
is8 = is_8bit_register(o1[0])
ss = [x for x, y in regs.regs.items() if x != o1[0] and y is not None and y == regs.get(o1[1]) and
not is_8bit_register(o1[1])]
for r_ in ss:
if is8 != is_8bit_register(r_):
continue
changed = True
if is8: # ld A, n; ld B, n => ld A, n; ld B, A
self[i] = 'ld %s, %s' % (o1[0], r_)
else: # ld HL, n; ld DE, n => ld HL, n; ld d, h; ld e, l
# 16 bit register
self[i] = 'ld %s, %s' % (HI16(o1[0]), HI16(r_))
self.insert(i + 1, 'ld %s, %s' % (LO16(o1[0]), LO16(r_)))
break
if changed:
break
if OPT26 and i1 == i2 == 'ld' and (o1[0], o1[1], o2[0], o2[1]) == ('d', 'h', 'e', 'l') and \
not self.is_used(['h', 'l'], i + 2):
self[i] = 'ex de, hl'
self.pop(i + 1)
changed = True
break
if OPT27 and i1 in ('cp', 'or', 'and', 'add', 'adc', 'sub', 'sbc') and o1[-1] != 'a' and \
not self.is_used(o1[-1], i + 1) and i0 == 'ld' and o0[0] == o1[-1] and \
(o0[1] == '(hl)' or RE_IXIND.match(o0[1])):
template = '{0} %s{1}' % ('a, ' if i1 in ('add', 'adc', 'sbc') else '')
self[i] = template.format(i1, o0[1])
self.pop(i - 1)
changed = True
break
regs.op(i1, o1) | Tries to detect peep-hole patterns in this basic block
and remove them. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1674-L2037 |
boriel/zxbasic | arch/zx48k/backend/__str.py | _str_oper | def _str_oper(op1, op2=None, reversed=False, no_exaf=False):
''' Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
You can swap operators extraction order
by setting reversed to True.
If no_exaf = True => No bits flags in A' will be used.
This saves two bytes.
'''
output = []
if op2 is not None and reversed:
op1, op2 = op2, op1
tmp2 = False
if op2 is not None:
val = op2
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld de, (%s)' % val)
elif val[0] == '#': # Direct
output.append('ld de, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop de')
else:
output.append('pop de')
tmp2 = True
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm') # TODO: This is never used??
if reversed:
tmp = output
output = []
val = op1
tmp1 = False
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld hl, (%s)' % val)
elif val[0] == '#': # Inmmediate
output.append('ld hl, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop hl')
else:
output.append('pop hl')
tmp1 = True
if indirect:
output.append('ld hl, %s' % val[1:])
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
if reversed:
output.extend(tmp)
if not no_exaf:
if tmp1 and tmp2:
output.append('ld a, 3') # Marks both strings to be freed
elif tmp1:
output.append('ld a, 1') # Marks str1 to be freed
elif tmp2:
output.append('ld a, 2') # Marks str2 to be freed
else:
output.append('xor a') # Marks no string to be freed
if op2 is not None:
return (tmp1, tmp2, output)
return (tmp1, output) | python | def _str_oper(op1, op2=None, reversed=False, no_exaf=False):
''' Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
You can swap operators extraction order
by setting reversed to True.
If no_exaf = True => No bits flags in A' will be used.
This saves two bytes.
'''
output = []
if op2 is not None and reversed:
op1, op2 = op2, op1
tmp2 = False
if op2 is not None:
val = op2
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld de, (%s)' % val)
elif val[0] == '#': # Direct
output.append('ld de, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop de')
else:
output.append('pop de')
tmp2 = True
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm') # TODO: This is never used??
if reversed:
tmp = output
output = []
val = op1
tmp1 = False
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld hl, (%s)' % val)
elif val[0] == '#': # Inmmediate
output.append('ld hl, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop hl')
else:
output.append('pop hl')
tmp1 = True
if indirect:
output.append('ld hl, %s' % val[1:])
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
if reversed:
output.extend(tmp)
if not no_exaf:
if tmp1 and tmp2:
output.append('ld a, 3') # Marks both strings to be freed
elif tmp1:
output.append('ld a, 1') # Marks str1 to be freed
elif tmp2:
output.append('ld a, 2') # Marks str2 to be freed
else:
output.append('xor a') # Marks no string to be freed
if op2 is not None:
return (tmp1, tmp2, output)
return (tmp1, output) | Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
You can swap operators extraction order
by setting reversed to True.
If no_exaf = True => No bits flags in A' will be used.
This saves two bytes. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__str.py#L16-L99 |
boriel/zxbasic | arch/zx48k/backend/__str.py | _free_sequence | def _free_sequence(tmp1, tmp2=False):
''' Outputs a FREEMEM sequence for 1 or 2 ops
'''
if not tmp1 and not tmp2:
return []
output = []
if tmp1 and tmp2:
output.append('pop de')
output.append('ex (sp), hl')
output.append('push de')
output.append('call __MEM_FREE')
output.append('pop hl')
output.append('call __MEM_FREE')
else:
output.append('ex (sp), hl')
output.append('call __MEM_FREE')
output.append('pop hl')
REQUIRES.add('alloc.asm')
return output | python | def _free_sequence(tmp1, tmp2=False):
''' Outputs a FREEMEM sequence for 1 or 2 ops
'''
if not tmp1 and not tmp2:
return []
output = []
if tmp1 and tmp2:
output.append('pop de')
output.append('ex (sp), hl')
output.append('push de')
output.append('call __MEM_FREE')
output.append('pop hl')
output.append('call __MEM_FREE')
else:
output.append('ex (sp), hl')
output.append('call __MEM_FREE')
output.append('pop hl')
REQUIRES.add('alloc.asm')
return output | Outputs a FREEMEM sequence for 1 or 2 ops | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__str.py#L102-L122 |
boriel/zxbasic | arch/zx48k/backend/__str.py | _nestr | def _nestr(ins):
''' Compares & pops top 2 strings out of the stack.
Temporal values are freed from memory. (a$ != b$)
'''
(tmp1, tmp2, output) = _str_oper(ins.quad[2], ins.quad[3])
output.append('call __STRNE')
output.append('push af')
REQUIRES.add('string.asm')
return output | python | def _nestr(ins):
''' Compares & pops top 2 strings out of the stack.
Temporal values are freed from memory. (a$ != b$)
'''
(tmp1, tmp2, output) = _str_oper(ins.quad[2], ins.quad[3])
output.append('call __STRNE')
output.append('push af')
REQUIRES.add('string.asm')
return output | Compares & pops top 2 strings out of the stack.
Temporal values are freed from memory. (a$ != b$) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__str.py#L199-L207 |
boriel/zxbasic | arch/zx48k/backend/__str.py | _lenstr | def _lenstr(ins):
''' Returns string length
'''
(tmp1, output) = _str_oper(ins.quad[2], no_exaf=True)
if tmp1:
output.append('push hl')
output.append('call __STRLEN')
output.extend(_free_sequence(tmp1))
output.append('push hl')
REQUIRES.add('strlen.asm')
return output | python | def _lenstr(ins):
''' Returns string length
'''
(tmp1, output) = _str_oper(ins.quad[2], no_exaf=True)
if tmp1:
output.append('push hl')
output.append('call __STRLEN')
output.extend(_free_sequence(tmp1))
output.append('push hl')
REQUIRES.add('strlen.asm')
return output | Returns string length | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__str.py#L210-L221 |
boriel/zxbasic | symbols/builtin.py | SymbolBUILTIN.make_node | def make_node(cls, lineno, fname, func=None, type_=None, *operands):
""" Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string'
"""
if func is not None and len(operands) == 1: # Try constant-folding
if is_number(operands[0]) or is_string(operands[0]): # e.g. ABS(-5)
return SymbolNUMBER(func(operands[0].value), type_=type_, lineno=lineno)
return cls(lineno, fname, type_, *operands) | python | def make_node(cls, lineno, fname, func=None, type_=None, *operands):
""" Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string'
"""
if func is not None and len(operands) == 1: # Try constant-folding
if is_number(operands[0]) or is_string(operands[0]): # e.g. ABS(-5)
return SymbolNUMBER(func(operands[0].value), type_=type_, lineno=lineno)
return cls(lineno, fname, type_, *operands) | Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string' | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/builtin.py#L70-L83 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _8bit_oper | def _8bit_oper(op1, op2=None, reversed_=False):
""" Returns pop sequence for 8 bits operands
1st operand in H, 2nd operand in A (accumulator)
For some operations (like comparisons), you can swap
operands extraction by setting reversed = True
"""
output = []
if op2 is not None and reversed_:
tmp = op1
op1 = op2
op2 = tmp
op = op1
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld a, (%i)' % op)
else:
if op == 0:
output.append('xor a')
else:
output.append('ld a, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld a, (%s)' % op)
else:
output.append('ld a, %s' % op)
elif op[0] == '_':
if indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('ld %s, (%s)' % (idx, op)) # can't use HL
output.append('ld a, (%s)' % idx)
else:
output.append('ld a, (%s)' % op)
else:
if immediate:
output.append('ld a, %s' % op)
elif indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('pop %s' % idx)
output.append('ld a, (%s)' % idx)
else:
output.append('pop af')
if op2 is None:
return output
if not reversed_:
tmp = output
output = []
op = op2
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld hl, (%i - 1)' % op)
else:
output.append('ld h, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld hl, %s' % op)
output.append('ld h, (hl)')
else:
output.append('ld h, %s' % op)
elif op[0] == '_':
if indirect:
output.append('ld hl, (%s)' % op)
output.append('ld h, (hl)' % op)
else:
output.append('ld hl, (%s - 1)' % op)
else:
output.append('pop hl')
if indirect:
output.append('ld h, (hl)')
if not reversed_:
output.extend(tmp)
return output | python | def _8bit_oper(op1, op2=None, reversed_=False):
""" Returns pop sequence for 8 bits operands
1st operand in H, 2nd operand in A (accumulator)
For some operations (like comparisons), you can swap
operands extraction by setting reversed = True
"""
output = []
if op2 is not None and reversed_:
tmp = op1
op1 = op2
op2 = tmp
op = op1
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld a, (%i)' % op)
else:
if op == 0:
output.append('xor a')
else:
output.append('ld a, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld a, (%s)' % op)
else:
output.append('ld a, %s' % op)
elif op[0] == '_':
if indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('ld %s, (%s)' % (idx, op)) # can't use HL
output.append('ld a, (%s)' % idx)
else:
output.append('ld a, (%s)' % op)
else:
if immediate:
output.append('ld a, %s' % op)
elif indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('pop %s' % idx)
output.append('ld a, (%s)' % idx)
else:
output.append('pop af')
if op2 is None:
return output
if not reversed_:
tmp = output
output = []
op = op2
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld hl, (%i - 1)' % op)
else:
output.append('ld h, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld hl, %s' % op)
output.append('ld h, (hl)')
else:
output.append('ld h, %s' % op)
elif op[0] == '_':
if indirect:
output.append('ld hl, (%s)' % op)
output.append('ld h, (hl)' % op)
else:
output.append('ld hl, (%s - 1)' % op)
else:
output.append('pop hl')
if indirect:
output.append('ld h, (hl)')
if not reversed_:
output.extend(tmp)
return output | Returns pop sequence for 8 bits operands
1st operand in H, 2nd operand in A (accumulator)
For some operations (like comparisons), you can swap
operands extraction by setting reversed = True | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L23-L124 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _add8 | def _add8(ins):
""" Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
* If any of the operands is 1, then
INC is used
* If any of the operands is -1 (255), then
DEC is used
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 0: # Nothing to add: A + 0 = A
output.append('push af')
return output
op2 = int8(op2)
if op2 == 1: # Adding 1 is just an inc
output.append('inc a')
output.append('push af')
return output
if op2 == 0xFF: # Adding 255 is just a dec
output.append('dec a')
output.append('push af')
return output
output.append('add a, %i' % int8(op2))
output.append('push af')
return output
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('add a, h')
output.append('push af')
return output | python | def _add8(ins):
""" Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
* If any of the operands is 1, then
INC is used
* If any of the operands is -1 (255), then
DEC is used
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 0: # Nothing to add: A + 0 = A
output.append('push af')
return output
op2 = int8(op2)
if op2 == 1: # Adding 1 is just an inc
output.append('inc a')
output.append('push af')
return output
if op2 == 0xFF: # Adding 255 is just a dec
output.append('dec a')
output.append('push af')
return output
output.append('add a, %i' % int8(op2))
output.append('push af')
return output
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('add a, h')
output.append('push af')
return output | Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
* If any of the operands is 1, then
INC is used
* If any of the operands is -1 (255), then
DEC is used | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L127-L173 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _sub8 | def _sub8(ins):
""" Pops last 2 bytes from the stack and subtract them.
Then push the result onto the stack. Top-1 of the stack is
subtracted Top
_sub8 t1, a, b === t1 <-- a - b
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If 1st operand is 0, then
just do a NEG
* If any of the operands is 1, then
DEC is used
* If any of the operands is -1 (255), then
INC is used
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2): # 2nd operand
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 0:
output.append('push af')
return output # A - 0 = A
op2 = int8(op2)
if op2 == 1: # A - 1 == DEC A
output.append('dec a')
output.append('push af')
return output
if op2 == 0xFF: # A - (-1) == INC A
output.append('inc a')
output.append('push af')
return output
output.append('sub %i' % op2)
output.append('push af')
return output
if is_int(op1): # 1st operand is numeric?
if int8(op1) == 0: # 0 - A = -A ==> NEG A
output = _8bit_oper(op2)
output.append('neg')
output.append('push af')
return output
# At this point, even if 1st operand is numeric, proceed
# normally
if op2[0] == '_': # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('sub h')
output.append('push af')
return output | python | def _sub8(ins):
""" Pops last 2 bytes from the stack and subtract them.
Then push the result onto the stack. Top-1 of the stack is
subtracted Top
_sub8 t1, a, b === t1 <-- a - b
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If 1st operand is 0, then
just do a NEG
* If any of the operands is 1, then
DEC is used
* If any of the operands is -1 (255), then
INC is used
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2): # 2nd operand
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 0:
output.append('push af')
return output # A - 0 = A
op2 = int8(op2)
if op2 == 1: # A - 1 == DEC A
output.append('dec a')
output.append('push af')
return output
if op2 == 0xFF: # A - (-1) == INC A
output.append('inc a')
output.append('push af')
return output
output.append('sub %i' % op2)
output.append('push af')
return output
if is_int(op1): # 1st operand is numeric?
if int8(op1) == 0: # 0 - A = -A ==> NEG A
output = _8bit_oper(op2)
output.append('neg')
output.append('push af')
return output
# At this point, even if 1st operand is numeric, proceed
# normally
if op2[0] == '_': # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('sub h')
output.append('push af')
return output | Pops last 2 bytes from the stack and subtract them.
Then push the result onto the stack. Top-1 of the stack is
subtracted Top
_sub8 t1, a, b === t1 <-- a - b
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If 1st operand is 0, then
just do a NEG
* If any of the operands is 1, then
DEC is used
* If any of the operands is -1 (255), then
INC is used | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L176-L241 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _mul8 | def _mul8(ins):
""" Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 1: # A * 1 = 1 * A = A
output.append('push af')
return output
if op2 == 0:
output.append('xor a')
output.append('push af')
return output
if op2 == 2: # A * 2 == A SLA 1
output.append('add a, a')
output.append('push af')
return output
if op2 == 4: # A * 4 == A SLA 2
output.append('add a, a')
output.append('add a, a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('call __MUL8_FAST') # Inmmediate
output.append('push af')
REQUIRES.add('mul8.asm')
return output | python | def _mul8(ins):
""" Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 1: # A * 1 = 1 * A = A
output.append('push af')
return output
if op2 == 0:
output.append('xor a')
output.append('push af')
return output
if op2 == 2: # A * 2 == A SLA 1
output.append('add a, a')
output.append('push af')
return output
if op2 == 4: # A * 4 == A SLA 2
output.append('add a, a')
output.append('add a, a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('call __MUL8_FAST') # Inmmediate
output.append('push af')
REQUIRES.add('mul8.asm')
return output | Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L244-L290 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _divu8 | def _divu8(ins):
""" Divides 2 8bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 1:
output.append('push af')
return output
if op2 == 2:
output.append('srl a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # Optimization when 2nd operand is an id
if is_int(op1) and int(op1) == 0:
output = list() # Optimization: Discard previous op if not from the stack
output.append('xor a')
output.append('push af')
return output
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('call __DIVU8_FAST')
output.append('push af')
REQUIRES.add('div8.asm')
return output | python | def _divu8(ins):
""" Divides 2 8bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 1:
output.append('push af')
return output
if op2 == 2:
output.append('srl a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # Optimization when 2nd operand is an id
if is_int(op1) and int(op1) == 0:
output = list() # Optimization: Discard previous op if not from the stack
output.append('xor a')
output.append('push af')
return output
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('call __DIVU8_FAST')
output.append('push af')
REQUIRES.add('div8.asm')
return output | Divides 2 8bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L293-L336 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _ltu8 | def _ltu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('cp h')
output.append('sbc a, a')
output.append('push af')
return output | python | def _ltu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('cp h')
output.append('sbc a, a')
output.append('push af')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L490-L502 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _lti8 | def _lti8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = []
output.extend(_8bit_oper(ins.quad[2], ins.quad[3]))
output.append('call __LTI8')
output.append('push af')
REQUIRES.add('lti8.asm')
return output | python | def _lti8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = []
output.extend(_8bit_oper(ins.quad[2], ins.quad[3]))
output.append('call __LTI8')
output.append('push af')
REQUIRES.add('lti8.asm')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L505-L518 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _gtu8 | def _gtu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('cp h')
output.append('sbc a, a')
output.append('push af')
return output | python | def _gtu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('cp h')
output.append('sbc a, a')
output.append('push af')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L521-L533 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _eq8 | def _eq8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand == 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit un/signed version
"""
if is_int(ins.quad[3]):
output = _8bit_oper(ins.quad[2])
n = int8(ins.quad[3])
if n:
if n == 1:
output.append('dec a')
else:
output.append('sub %i' % n)
else:
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('sub h')
output.append('sub 1') # Sets Carry only if 0
output.append('sbc a, a')
output.append('push af')
return output | python | def _eq8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand == 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit un/signed version
"""
if is_int(ins.quad[3]):
output = _8bit_oper(ins.quad[2])
n = int8(ins.quad[3])
if n:
if n == 1:
output.append('dec a')
else:
output.append('sub %i' % n)
else:
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('sub h')
output.append('sub 1') # Sets Carry only if 0
output.append('sbc a, a')
output.append('push af')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand == 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit un/signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L551-L574 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _leu8 | def _leu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('sub h') # Carry if H > A
output.append('ccf') # Negates => Carry if H <= A
output.append('sbc a, a')
output.append('push af')
return output | python | def _leu8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('sub h') # Carry if H > A
output.append('ccf') # Negates => Carry if H <= A
output.append('sbc a, a')
output.append('push af')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L577-L590 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _lei8 | def _lei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('call __LEI8')
output.append('push af')
REQUIRES.add('lei8.asm')
return output | python | def _lei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('call __LEI8')
output.append('push af')
REQUIRES.add('lei8.asm')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L593-L605 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _gei8 | def _gei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('call __LEI8')
output.append('push af')
REQUIRES.add('lei8.asm')
return output | python | def _gei8(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version
"""
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('call __LEI8')
output.append('push af')
REQUIRES.add('lei8.asm')
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L633-L645 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _and8 | def _and8(ins):
""" Pops top 2 operands out of the stack, and checks
if 1st operand AND (logical) 2nd operand (top of the stack),
pushes 0 if False, not 0 if True.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1) # Pops the stack (if applicable)
if op2 != 0: # X and True = X
output.append('push af')
return output
# False and X = False
output.append('xor a')
output.append('push af')
return output
output = _8bit_oper(op1, op2)
# output.append('call __AND8')
lbl = tmp_label()
output.append('or a')
output.append('jr z, %s' % lbl)
output.append('ld a, h')
output.append('%s:' % lbl)
output.append('push af')
# REQUIRES.add('and8.asm')
return output | python | def _and8(ins):
""" Pops top 2 operands out of the stack, and checks
if 1st operand AND (logical) 2nd operand (top of the stack),
pushes 0 if False, not 0 if True.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1) # Pops the stack (if applicable)
if op2 != 0: # X and True = X
output.append('push af')
return output
# False and X = False
output.append('xor a')
output.append('push af')
return output
output = _8bit_oper(op1, op2)
# output.append('call __AND8')
lbl = tmp_label()
output.append('or a')
output.append('jr z, %s' % lbl)
output.append('ld a, h')
output.append('%s:' % lbl)
output.append('push af')
# REQUIRES.add('and8.asm')
return output | Pops top 2 operands out of the stack, and checks
if 1st operand AND (logical) 2nd operand (top of the stack),
pushes 0 if False, not 0 if True.
8 bit un/signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L730-L761 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _band8 | def _band8(ins):
""" Pops top 2 operands out of the stack, and does
1st AND (bitwise) 2nd operand (top of the stack),
pushes the result.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 0xFF: # X & 0xFF = X
output.append('push af')
return output
if op2 == 0: # X and 0 = 0
output.append('xor a')
output.append('push af')
return output
op1, op2 = tuple(ins.quad[2:])
output = _8bit_oper(op1, op2)
output.append('and h')
output.append('push af')
return output | python | def _band8(ins):
""" Pops top 2 operands out of the stack, and does
1st AND (bitwise) 2nd operand (top of the stack),
pushes the result.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 0xFF: # X & 0xFF = X
output.append('push af')
return output
if op2 == 0: # X and 0 = 0
output.append('xor a')
output.append('push af')
return output
op1, op2 = tuple(ins.quad[2:])
output = _8bit_oper(op1, op2)
output.append('and h')
output.append('push af')
return output | Pops top 2 operands out of the stack, and does
1st AND (bitwise) 2nd operand (top of the stack),
pushes the result.
8 bit un/signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L764-L791 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _xor8 | def _xor8(ins):
""" Pops top 2 operands out of the stack, and checks
if 1st operand XOR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1) # True or X = not X
if op2 == 0: # False xor X = X
output.append('push af')
return output
output.append('sub 1')
output.append('sbc a, a')
output.append('push af')
return output
output = _8bit_oper(op1, op2)
output.append('call __XOR8')
output.append('push af')
REQUIRES.add('xor8.asm')
return output | python | def _xor8(ins):
""" Pops top 2 operands out of the stack, and checks
if 1st operand XOR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1) # True or X = not X
if op2 == 0: # False xor X = X
output.append('push af')
return output
output.append('sub 1')
output.append('sbc a, a')
output.append('push af')
return output
output = _8bit_oper(op1, op2)
output.append('call __XOR8')
output.append('push af')
REQUIRES.add('xor8.asm')
return output | Pops top 2 operands out of the stack, and checks
if 1st operand XOR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
8 bit un/signed version | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L794-L820 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _not8 | def _not8(ins):
""" Negates (Logical NOT) top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('sub 1') # Gives carry only if A = 0
output.append('sbc a, a') # Gives FF only if Carry else 0
output.append('push af')
return output | python | def _not8(ins):
""" Negates (Logical NOT) top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('sub 1') # Gives carry only if A = 0
output.append('sbc a, a') # Gives FF only if Carry else 0
output.append('push af')
return output | Negates (Logical NOT) top of the stack (8 bits in AF) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L853-L861 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _bnot8 | def _bnot8(ins):
""" Negates (BITWISE NOT) top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('cpl') # Gives carry only if A = 0
output.append('push af')
return output | python | def _bnot8(ins):
""" Negates (BITWISE NOT) top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('cpl') # Gives carry only if A = 0
output.append('push af')
return output | Negates (BITWISE NOT) top of the stack (8 bits in AF) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L864-L871 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _neg8 | def _neg8(ins):
""" Negates top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('neg')
output.append('push af')
return output | python | def _neg8(ins):
""" Negates top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('neg')
output.append('push af')
return output | Negates top of the stack (8 bits in AF) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L874-L881 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _abs8 | def _abs8(ins):
""" Absolute value of top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('call __ABS8')
output.append('push af')
REQUIRES.add('abs8.asm')
return output | python | def _abs8(ins):
""" Absolute value of top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('call __ABS8')
output.append('push af')
REQUIRES.add('abs8.asm')
return output | Absolute value of top of the stack (8 bits in AF) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L884-L891 |
boriel/zxbasic | arch/zx48k/backend/__8bit.py | _shru8 | def _shru8(ins):
""" Shift 8bit unsigned integer to the right. The result is pushed onto the stack.
Optimizations:
* If 1nd or 2nd op is 0 then
do nothing
* If 2nd op is < 4 then
unroll loop
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 0:
output.append('push af')
return output
if op2 < 4:
output.extend(['srl a'] * op2)
output.append('push af')
return output
label = tmp_label()
output.append('ld b, %i' % int8(op2))
output.append('%s:' % label)
output.append('srl a')
output.append('djnz %s' % label)
output.append('push af')
return output
if is_int(op1) and int(op1) == 0:
output = _8bit_oper(op2)
output.append('xor a')
output.append('push af')
return output
output = _8bit_oper(op1, op2, True)
label = tmp_label()
label2 = tmp_label()
output.append('or a')
output.append('ld b, a')
output.append('ld a, h')
output.append('jr z, %s' % label2)
output.append('%s:' % label)
output.append('srl a')
output.append('djnz %s' % label)
output.append('%s:' % label2)
output.append('push af')
return output | python | def _shru8(ins):
""" Shift 8bit unsigned integer to the right. The result is pushed onto the stack.
Optimizations:
* If 1nd or 2nd op is 0 then
do nothing
* If 2nd op is < 4 then
unroll loop
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 0:
output.append('push af')
return output
if op2 < 4:
output.extend(['srl a'] * op2)
output.append('push af')
return output
label = tmp_label()
output.append('ld b, %i' % int8(op2))
output.append('%s:' % label)
output.append('srl a')
output.append('djnz %s' % label)
output.append('push af')
return output
if is_int(op1) and int(op1) == 0:
output = _8bit_oper(op2)
output.append('xor a')
output.append('push af')
return output
output = _8bit_oper(op1, op2, True)
label = tmp_label()
label2 = tmp_label()
output.append('or a')
output.append('ld b, a')
output.append('ld a, h')
output.append('jr z, %s' % label2)
output.append('%s:' % label)
output.append('srl a')
output.append('djnz %s' % label)
output.append('%s:' % label2)
output.append('push af')
return output | Shift 8bit unsigned integer to the right. The result is pushed onto the stack.
Optimizations:
* If 1nd or 2nd op is 0 then
do nothing
* If 2nd op is < 4 then
unroll loop | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L894-L945 |
boriel/zxbasic | prepro/macrocall.py | MacroCall.is_defined | def is_defined(self, symbolTable=None):
""" True if this macro has been defined
"""
if symbolTable is None:
symbolTable = self.table
return symbolTable.defined(self.id_) | python | def is_defined(self, symbolTable=None):
""" True if this macro has been defined
"""
if symbolTable is None:
symbolTable = self.table
return symbolTable.defined(self.id_) | True if this macro has been defined | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/macrocall.py#L89-L95 |
boriel/zxbasic | symbols/boundlist.py | SymbolBOUNDLIST.make_node | def make_node(cls, node, *args):
''' Creates an array BOUND LIST.
'''
if node is None:
return cls.make_node(SymbolBOUNDLIST(), *args)
if node.token != 'BOUNDLIST':
return cls.make_node(None, node, *args)
for arg in args:
if arg is None:
continue
node.appendChild(arg)
return node | python | def make_node(cls, node, *args):
''' Creates an array BOUND LIST.
'''
if node is None:
return cls.make_node(SymbolBOUNDLIST(), *args)
if node.token != 'BOUNDLIST':
return cls.make_node(None, node, *args)
for arg in args:
if arg is None:
continue
node.appendChild(arg)
return node | Creates an array BOUND LIST. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/boundlist.py#L35-L49 |
boriel/zxbasic | zxbparser.py | init | def init():
""" Initializes parser state
"""
global LABELS
global LET_ASSIGNMENT
global PRINT_IS_USED
global SYMBOL_TABLE
global ast
global data_ast
global optemps
global OPTIONS
global last_brk_linenum
LABELS = {}
LET_ASSIGNMENT = False
PRINT_IS_USED = False
last_brk_linenum = 0
ast = None
data_ast = None # Global Variables AST
optemps = OpcodesTemps()
gl.INITS.clear()
del gl.FUNCTION_CALLS[:]
del gl.FUNCTION_LEVEL[:]
del gl.FUNCTIONS[:]
SYMBOL_TABLE = gl.SYMBOL_TABLE = api.symboltable.SymbolTable()
OPTIONS = api.config.OPTIONS
# DATAs info
gl.DATA_LABELS.clear()
gl.DATA_IS_USED = False
del gl.DATAS[:]
gl.DATA_PTR_CURRENT = api.utils.current_data_label()
gl.DATA_FUNCTIONS = []
gl.error_msg_cache.clear() | python | def init():
""" Initializes parser state
"""
global LABELS
global LET_ASSIGNMENT
global PRINT_IS_USED
global SYMBOL_TABLE
global ast
global data_ast
global optemps
global OPTIONS
global last_brk_linenum
LABELS = {}
LET_ASSIGNMENT = False
PRINT_IS_USED = False
last_brk_linenum = 0
ast = None
data_ast = None # Global Variables AST
optemps = OpcodesTemps()
gl.INITS.clear()
del gl.FUNCTION_CALLS[:]
del gl.FUNCTION_LEVEL[:]
del gl.FUNCTIONS[:]
SYMBOL_TABLE = gl.SYMBOL_TABLE = api.symboltable.SymbolTable()
OPTIONS = api.config.OPTIONS
# DATAs info
gl.DATA_LABELS.clear()
gl.DATA_IS_USED = False
del gl.DATAS[:]
gl.DATA_PTR_CURRENT = api.utils.current_data_label()
gl.DATA_FUNCTIONS = []
gl.error_msg_cache.clear() | Initializes parser state | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L113-L149 |
boriel/zxbasic | zxbparser.py | make_number | def make_number(value, lineno, type_=None):
""" Wrapper: creates a constant number node.
"""
return symbols.NUMBER(value, type_=type_, lineno=lineno) | python | def make_number(value, lineno, type_=None):
""" Wrapper: creates a constant number node.
"""
return symbols.NUMBER(value, type_=type_, lineno=lineno) | Wrapper: creates a constant number node. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L171-L174 |
boriel/zxbasic | zxbparser.py | make_typecast | def make_typecast(type_, node, lineno):
""" Wrapper: returns a Typecast node
"""
assert isinstance(type_, symbols.TYPE)
return symbols.TYPECAST.make_node(type_, node, lineno) | python | def make_typecast(type_, node, lineno):
""" Wrapper: returns a Typecast node
"""
assert isinstance(type_, symbols.TYPE)
return symbols.TYPECAST.make_node(type_, node, lineno) | Wrapper: returns a Typecast node | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L177-L181 |
boriel/zxbasic | zxbparser.py | make_binary | def make_binary(lineno, operator, left, right, func=None, type_=None):
""" Wrapper: returns a Binary node
"""
return symbols.BINARY.make_node(operator, left, right, lineno, func, type_) | python | def make_binary(lineno, operator, left, right, func=None, type_=None):
""" Wrapper: returns a Binary node
"""
return symbols.BINARY.make_node(operator, left, right, lineno, func, type_) | Wrapper: returns a Binary node | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L184-L187 |
boriel/zxbasic | zxbparser.py | make_unary | def make_unary(lineno, operator, operand, func=None, type_=None):
""" Wrapper: returns a Unary node
"""
return symbols.UNARY.make_node(lineno, operator, operand, func, type_) | python | def make_unary(lineno, operator, operand, func=None, type_=None):
""" Wrapper: returns a Unary node
"""
return symbols.UNARY.make_node(lineno, operator, operand, func, type_) | Wrapper: returns a Unary node | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L190-L193 |
boriel/zxbasic | zxbparser.py | make_builtin | def make_builtin(lineno, fname, operands, func=None, type_=None):
""" Wrapper: returns a Builtin function node.
Can be a Symbol, tuple or list of Symbols
If operand is an iterable, they will be expanded.
"""
if operands is None:
operands = []
assert isinstance(operands, Symbol) or isinstance(operands, tuple) or isinstance(operands, list)
# TODO: In the future, builtin functions will be implemented in an external library, like POINT or ATTR
__DEBUG__('Creating BUILTIN "{}"'.format(fname), 1)
if not isinstance(operands, collections.Iterable):
operands = [operands]
return symbols.BUILTIN.make_node(lineno, fname, func, type_, *operands) | python | def make_builtin(lineno, fname, operands, func=None, type_=None):
""" Wrapper: returns a Builtin function node.
Can be a Symbol, tuple or list of Symbols
If operand is an iterable, they will be expanded.
"""
if operands is None:
operands = []
assert isinstance(operands, Symbol) or isinstance(operands, tuple) or isinstance(operands, list)
# TODO: In the future, builtin functions will be implemented in an external library, like POINT or ATTR
__DEBUG__('Creating BUILTIN "{}"'.format(fname), 1)
if not isinstance(operands, collections.Iterable):
operands = [operands]
return symbols.BUILTIN.make_node(lineno, fname, func, type_, *operands) | Wrapper: returns a Builtin function node.
Can be a Symbol, tuple or list of Symbols
If operand is an iterable, they will be expanded. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L196-L208 |
boriel/zxbasic | zxbparser.py | make_strslice | def make_strslice(lineno, s, lower, upper):
""" Wrapper: returns String Slice node
"""
return symbols.STRSLICE.make_node(lineno, s, lower, upper) | python | def make_strslice(lineno, s, lower, upper):
""" Wrapper: returns String Slice node
"""
return symbols.STRSLICE.make_node(lineno, s, lower, upper) | Wrapper: returns String Slice node | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L215-L218 |
boriel/zxbasic | zxbparser.py | make_sentence | def make_sentence(sentence, *args, **kwargs):
""" Wrapper: returns a Sentence node
"""
return symbols.SENTENCE(*([sentence] + list(args)), **kwargs) | python | def make_sentence(sentence, *args, **kwargs):
""" Wrapper: returns a Sentence node
"""
return symbols.SENTENCE(*([sentence] + list(args)), **kwargs) | Wrapper: returns a Sentence node | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L221-L224 |
boriel/zxbasic | zxbparser.py | make_func_declaration | def make_func_declaration(func_name, lineno, type_=None):
""" This will return a node with the symbol as a function.
"""
return symbols.FUNCDECL.make_node(func_name, lineno, type_=type_) | python | def make_func_declaration(func_name, lineno, type_=None):
""" This will return a node with the symbol as a function.
"""
return symbols.FUNCDECL.make_node(func_name, lineno, type_=type_) | This will return a node with the symbol as a function. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L252-L255 |
boriel/zxbasic | zxbparser.py | make_argument | def make_argument(expr, lineno, byref=None):
""" Wrapper: Creates a node containing an ARGUMENT
"""
if expr is None:
return # There were a syntax / semantic error
if byref is None:
byref = OPTIONS.byref.value
return symbols.ARGUMENT(expr, lineno=lineno, byref=byref) | python | def make_argument(expr, lineno, byref=None):
""" Wrapper: Creates a node containing an ARGUMENT
"""
if expr is None:
return # There were a syntax / semantic error
if byref is None:
byref = OPTIONS.byref.value
return symbols.ARGUMENT(expr, lineno=lineno, byref=byref) | Wrapper: Creates a node containing an ARGUMENT | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L264-L272 |
boriel/zxbasic | zxbparser.py | make_sub_call | def make_sub_call(id_, lineno, params):
""" This will return an AST node for a sub/procedure call.
"""
return symbols.CALL.make_node(id_, params, lineno) | python | def make_sub_call(id_, lineno, params):
""" This will return an AST node for a sub/procedure call.
"""
return symbols.CALL.make_node(id_, params, lineno) | This will return an AST node for a sub/procedure call. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L281-L284 |
boriel/zxbasic | zxbparser.py | make_func_call | def make_func_call(id_, lineno, params):
""" This will return an AST node for a function call.
"""
return symbols.FUNCCALL.make_node(id_, params, lineno) | python | def make_func_call(id_, lineno, params):
""" This will return an AST node for a function call.
"""
return symbols.FUNCCALL.make_node(id_, params, lineno) | This will return an AST node for a function call. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L287-L290 |
boriel/zxbasic | zxbparser.py | make_array_access | def make_array_access(id_, lineno, arglist):
""" Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
"""
return symbols.ARRAYACCESS.make_node(id_, arglist, lineno) | python | def make_array_access(id_, lineno, arglist):
""" Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
"""
return symbols.ARRAYACCESS.make_node(id_, arglist, lineno) | Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L293-L297 |
boriel/zxbasic | zxbparser.py | make_call | def make_call(id_, lineno, args):
""" This will return an AST node for a function call/array access.
A "call" is just an ID followed by a list of arguments.
E.g. a(4)
- a(4) can be a function call if 'a' is a function
- a(4) can be a string slice if a is a string variable: a$(4)
- a(4) can be an access to an array if a is an array
This function will inspect the id_. If it is undeclared then
id_ will be taken as a forwarded function.
"""
assert isinstance(args, symbols.ARGLIST)
entry = SYMBOL_TABLE.access_call(id_, lineno)
if entry is None:
return None
if entry.class_ is CLASS.unknown and entry.type_ == TYPE.string and len(args) == 1 and is_numeric(args[0]):
entry.class_ = CLASS.var # A scalar variable. e.g a$(expr)
if entry.class_ == CLASS.array: # An already declared array
arr = symbols.ARRAYLOAD.make_node(id_, args, lineno)
if arr is None:
return None
if arr.offset is not None:
offset = make_typecast(TYPE.uinteger,
make_number(arr.offset, lineno=lineno),
lineno)
arr.appendChild(offset)
return arr
if entry.class_ == CLASS.var: # An already declared/used string var
if len(args) > 1:
api.errmsg.syntax_error_not_array_nor_func(lineno, id_)
return None
entry = SYMBOL_TABLE.access_var(id_, lineno)
if entry is None:
return None
if len(args) == 1:
return symbols.STRSLICE.make_node(lineno, entry, args[0].value, args[0].value)
entry.accessed = True
return entry
return make_func_call(id_, lineno, args) | python | def make_call(id_, lineno, args):
""" This will return an AST node for a function call/array access.
A "call" is just an ID followed by a list of arguments.
E.g. a(4)
- a(4) can be a function call if 'a' is a function
- a(4) can be a string slice if a is a string variable: a$(4)
- a(4) can be an access to an array if a is an array
This function will inspect the id_. If it is undeclared then
id_ will be taken as a forwarded function.
"""
assert isinstance(args, symbols.ARGLIST)
entry = SYMBOL_TABLE.access_call(id_, lineno)
if entry is None:
return None
if entry.class_ is CLASS.unknown and entry.type_ == TYPE.string and len(args) == 1 and is_numeric(args[0]):
entry.class_ = CLASS.var # A scalar variable. e.g a$(expr)
if entry.class_ == CLASS.array: # An already declared array
arr = symbols.ARRAYLOAD.make_node(id_, args, lineno)
if arr is None:
return None
if arr.offset is not None:
offset = make_typecast(TYPE.uinteger,
make_number(arr.offset, lineno=lineno),
lineno)
arr.appendChild(offset)
return arr
if entry.class_ == CLASS.var: # An already declared/used string var
if len(args) > 1:
api.errmsg.syntax_error_not_array_nor_func(lineno, id_)
return None
entry = SYMBOL_TABLE.access_var(id_, lineno)
if entry is None:
return None
if len(args) == 1:
return symbols.STRSLICE.make_node(lineno, entry, args[0].value, args[0].value)
entry.accessed = True
return entry
return make_func_call(id_, lineno, args) | This will return an AST node for a function call/array access.
A "call" is just an ID followed by a list of arguments.
E.g. a(4)
- a(4) can be a function call if 'a' is a function
- a(4) can be a string slice if a is a string variable: a$(4)
- a(4) can be an access to an array if a is an array
This function will inspect the id_. If it is undeclared then
id_ will be taken as a forwarded function. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L331-L379 |
boriel/zxbasic | zxbparser.py | make_type | def make_type(typename, lineno, implicit=False):
""" Converts a typename identifier (e.g. 'float') to
its internal symbol table entry representation.
Creates a type usage symbol stored in a AST
E.g. DIM a As Integer
will access Integer type
"""
assert isinstance(typename, str)
if not SYMBOL_TABLE.check_is_declared(typename, lineno, 'type'):
return None
type_ = symbols.TYPEREF(SYMBOL_TABLE.get_entry(typename), lineno, implicit)
return type_ | python | def make_type(typename, lineno, implicit=False):
""" Converts a typename identifier (e.g. 'float') to
its internal symbol table entry representation.
Creates a type usage symbol stored in a AST
E.g. DIM a As Integer
will access Integer type
"""
assert isinstance(typename, str)
if not SYMBOL_TABLE.check_is_declared(typename, lineno, 'type'):
return None
type_ = symbols.TYPEREF(SYMBOL_TABLE.get_entry(typename), lineno, implicit)
return type_ | Converts a typename identifier (e.g. 'float') to
its internal symbol table entry representation.
Creates a type usage symbol stored in a AST
E.g. DIM a As Integer
will access Integer type | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L388-L401 |
boriel/zxbasic | zxbparser.py | make_bound | def make_bound(lower, upper, lineno):
""" Wrapper: Creates an array bound
"""
return symbols.BOUND.make_node(lower, upper, lineno) | python | def make_bound(lower, upper, lineno):
""" Wrapper: Creates an array bound
"""
return symbols.BOUND.make_node(lower, upper, lineno) | Wrapper: Creates an array bound | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L404-L407 |
boriel/zxbasic | zxbparser.py | make_label | def make_label(id_, lineno):
""" Creates a label entry. Returns None on error.
"""
entry = SYMBOL_TABLE.declare_label(id_, lineno)
if entry:
gl.DATA_LABELS[id_] = gl.DATA_PTR_CURRENT # This label points to the current DATA block index
return entry | python | def make_label(id_, lineno):
""" Creates a label entry. Returns None on error.
"""
entry = SYMBOL_TABLE.declare_label(id_, lineno)
if entry:
gl.DATA_LABELS[id_] = gl.DATA_PTR_CURRENT # This label points to the current DATA block index
return entry | Creates a label entry. Returns None on error. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L416-L422 |
boriel/zxbasic | zxbparser.py | make_break | def make_break(lineno, p):
""" Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked """
global last_brk_linenum
if not OPTIONS.enableBreak.value or lineno == last_brk_linenum or is_null(p):
return None
last_brk_linenum = lineno
return make_sentence('CHKBREAK', make_number(lineno, lineno, TYPE.uinteger)) | python | def make_break(lineno, p):
""" Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked """
global last_brk_linenum
if not OPTIONS.enableBreak.value or lineno == last_brk_linenum or is_null(p):
return None
last_brk_linenum = lineno
return make_sentence('CHKBREAK', make_number(lineno, lineno, TYPE.uinteger)) | Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L425-L435 |
boriel/zxbasic | zxbparser.py | p_start | def p_start(p):
""" start : program
"""
global ast, data_ast
user_data = make_label('.ZXBASIC_USER_DATA', 0)
make_label('.ZXBASIC_USER_DATA_LEN', 0)
if PRINT_IS_USED:
zxbpp.ID_TABLE.define('___PRINT_IS_USED___', 1)
# zxbasmpp.ID_TABLE.define('___PRINT_IS_USED___', 1)
if zxblex.IN_STATE:
p.type = 'NEWLINE'
p_error(p)
sys.exit(1)
ast = p[0] = p[1]
__end = make_sentence('END', make_number(0, lineno=p.lexer.lineno))
if not is_null(ast):
ast.appendChild(__end)
else:
ast = __end
SYMBOL_TABLE.check_labels()
SYMBOL_TABLE.check_classes()
if gl.has_errors:
return
__DEBUG__('Checking pending labels', 1)
if not api.check.check_pending_labels(ast):
return
__DEBUG__('Checking pending calls', 1)
if not api.check.check_pending_calls():
return
data_ast = make_sentence('BLOCK', user_data)
# Appends variable declarations at the end.
for var in SYMBOL_TABLE.vars_:
data_ast.appendChild(make_var_declaration(var))
# Appends arrays declarations at the end.
for var in SYMBOL_TABLE.arrays:
data_ast.appendChild(make_array_declaration(var)) | python | def p_start(p):
""" start : program
"""
global ast, data_ast
user_data = make_label('.ZXBASIC_USER_DATA', 0)
make_label('.ZXBASIC_USER_DATA_LEN', 0)
if PRINT_IS_USED:
zxbpp.ID_TABLE.define('___PRINT_IS_USED___', 1)
# zxbasmpp.ID_TABLE.define('___PRINT_IS_USED___', 1)
if zxblex.IN_STATE:
p.type = 'NEWLINE'
p_error(p)
sys.exit(1)
ast = p[0] = p[1]
__end = make_sentence('END', make_number(0, lineno=p.lexer.lineno))
if not is_null(ast):
ast.appendChild(__end)
else:
ast = __end
SYMBOL_TABLE.check_labels()
SYMBOL_TABLE.check_classes()
if gl.has_errors:
return
__DEBUG__('Checking pending labels', 1)
if not api.check.check_pending_labels(ast):
return
__DEBUG__('Checking pending calls', 1)
if not api.check.check_pending_calls():
return
data_ast = make_sentence('BLOCK', user_data)
# Appends variable declarations at the end.
for var in SYMBOL_TABLE.vars_:
data_ast.appendChild(make_var_declaration(var))
# Appends arrays declarations at the end.
for var in SYMBOL_TABLE.arrays:
data_ast.appendChild(make_array_declaration(var)) | start : program | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L468-L515 |
boriel/zxbasic | zxbparser.py | p_program | def p_program(p):
""" program : program program_line
"""
p[0] = make_block(p[1], p[2], make_break(p.lineno(2), p[2])) | python | def p_program(p):
""" program : program program_line
"""
p[0] = make_block(p[1], p[2], make_break(p.lineno(2), p[2])) | program : program program_line | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L524-L527 |
boriel/zxbasic | zxbparser.py | p_statements_statement | def p_statements_statement(p):
""" statements : statement
| statements_co statement
"""
if len(p) == 2:
p[0] = make_block(p[1])
else:
p[0] = make_block(p[1], p[2]) | python | def p_statements_statement(p):
""" statements : statement
| statements_co statement
"""
if len(p) == 2:
p[0] = make_block(p[1])
else:
p[0] = make_block(p[1], p[2]) | statements : statement
| statements_co statement | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L563-L570 |
boriel/zxbasic | zxbparser.py | p_program_line_label | def p_program_line_label(p):
""" label_line : LABEL statements
| LABEL co_statements
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl | python | def p_program_line_label(p):
""" label_line : LABEL statements
| LABEL co_statements
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl | label_line : LABEL statements
| LABEL co_statements | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L579-L584 |
boriel/zxbasic | zxbparser.py | p_label_line_co | def p_label_line_co(p):
""" label_line_co : LABEL statements_co
| LABEL co_statements_co
| LABEL
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl | python | def p_label_line_co(p):
""" label_line_co : LABEL statements_co
| LABEL co_statements_co
| LABEL
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl | label_line_co : LABEL statements_co
| LABEL co_statements_co
| LABEL | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L593-L599 |
boriel/zxbasic | zxbparser.py | p_var_decl | def p_var_decl(p):
""" var_decl : DIM idlist typedef
"""
for vardata in p[2]:
SYMBOL_TABLE.declare_variable(vardata[0], vardata[1], p[3])
p[0] = None | python | def p_var_decl(p):
""" var_decl : DIM idlist typedef
"""
for vardata in p[2]:
SYMBOL_TABLE.declare_variable(vardata[0], vardata[1], p[3])
p[0] = None | var_decl : DIM idlist typedef | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L611-L617 |
boriel/zxbasic | zxbparser.py | p_var_decl_at | def p_var_decl_at(p):
""" var_decl : DIM idlist typedef AT expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1),
'Only one variable at a time can be declared this way')
return
idlist = p[2][0]
entry = SYMBOL_TABLE.declare_variable(idlist[0], idlist[1], p[3])
if entry is None:
return
if p[5].token == 'CONST':
tmp = p[5].expr
if tmp.token == 'UNARY' and tmp.operator == 'ADDRESS': # Must be an ID
if tmp.operand.token == 'VAR':
entry.make_alias(tmp.operand)
elif tmp.operand.token == 'ARRAYACCESS':
if tmp.operand.offset is None:
syntax_error(p.lineno(4), 'Address is not constant. Only constant subscripts are allowed')
return
entry.make_alias(tmp.operand)
entry.offset = tmp.operand.offset
else:
syntax_error(p.lineno(4), 'Only address of identifiers are allowed')
return
elif not is_number(p[5]):
syntax_error(p.lineno(4), 'Address must be a numeric constant expression')
return
else:
entry.addr = str(make_typecast(_TYPE(gl.STR_INDEX_TYPE), p[5], p.lineno(4)).value)
entry.accessed = True
if entry.scope == SCOPE.local:
SYMBOL_TABLE.make_static(entry.name) | python | def p_var_decl_at(p):
""" var_decl : DIM idlist typedef AT expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1),
'Only one variable at a time can be declared this way')
return
idlist = p[2][0]
entry = SYMBOL_TABLE.declare_variable(idlist[0], idlist[1], p[3])
if entry is None:
return
if p[5].token == 'CONST':
tmp = p[5].expr
if tmp.token == 'UNARY' and tmp.operator == 'ADDRESS': # Must be an ID
if tmp.operand.token == 'VAR':
entry.make_alias(tmp.operand)
elif tmp.operand.token == 'ARRAYACCESS':
if tmp.operand.offset is None:
syntax_error(p.lineno(4), 'Address is not constant. Only constant subscripts are allowed')
return
entry.make_alias(tmp.operand)
entry.offset = tmp.operand.offset
else:
syntax_error(p.lineno(4), 'Only address of identifiers are allowed')
return
elif not is_number(p[5]):
syntax_error(p.lineno(4), 'Address must be a numeric constant expression')
return
else:
entry.addr = str(make_typecast(_TYPE(gl.STR_INDEX_TYPE), p[5], p.lineno(4)).value)
entry.accessed = True
if entry.scope == SCOPE.local:
SYMBOL_TABLE.make_static(entry.name) | var_decl : DIM idlist typedef AT expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L620-L659 |
boriel/zxbasic | zxbparser.py | p_var_decl_ini | def p_var_decl_ini(p):
""" var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1),
"Initialized variables must be declared one by one.")
return
if p[5] is None:
return
if not is_static(p[5]):
if isinstance(p[5], symbols.UNARY):
p[5] = make_constexpr(p.lineno(4), p[5]) # Delayed constant evaluation
if p[3].implicit:
p[3] = symbols.TYPEREF(p[5].type_, p.lexer.lineno, implicit=True)
value = make_typecast(p[3], p[5], p.lineno(4))
defval = value if is_static(p[5]) else None
if p[1] == 'DIM':
SYMBOL_TABLE.declare_variable(p[2][0][0], p[2][0][1], p[3],
default_value=defval)
else:
SYMBOL_TABLE.declare_const(p[2][0][0], p[2][0][1], p[3],
default_value=defval)
if defval is None: # Okay do a delayed initialization
p[0] = make_sentence('LET', SYMBOL_TABLE.access_var(p[2][0][0], p.lineno(1)), value) | python | def p_var_decl_ini(p):
""" var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1),
"Initialized variables must be declared one by one.")
return
if p[5] is None:
return
if not is_static(p[5]):
if isinstance(p[5], symbols.UNARY):
p[5] = make_constexpr(p.lineno(4), p[5]) # Delayed constant evaluation
if p[3].implicit:
p[3] = symbols.TYPEREF(p[5].type_, p.lexer.lineno, implicit=True)
value = make_typecast(p[3], p[5], p.lineno(4))
defval = value if is_static(p[5]) else None
if p[1] == 'DIM':
SYMBOL_TABLE.declare_variable(p[2][0][0], p[2][0][1], p[3],
default_value=defval)
else:
SYMBOL_TABLE.declare_const(p[2][0][0], p[2][0][1], p[3],
default_value=defval)
if defval is None: # Okay do a delayed initialization
p[0] = make_sentence('LET', SYMBOL_TABLE.access_var(p[2][0][0], p.lineno(1)), value) | var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L662-L693 |
boriel/zxbasic | zxbparser.py | p_decl_arr | def p_decl_arr(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef
"""
if len(p[2]) != 1:
syntax_error(p.lineno(1), "Array declaration only allows one variable name at a time")
else:
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4])
p[0] = p[2][0] | python | def p_decl_arr(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef
"""
if len(p[2]) != 1:
syntax_error(p.lineno(1), "Array declaration only allows one variable name at a time")
else:
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4])
p[0] = p[2][0] | var_arr_decl : DIM idlist LP bound_list RP typedef | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L716-L724 |
boriel/zxbasic | zxbparser.py | p_arr_decl_initialized | def p_arr_decl_initialized(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector
"""
def check_bound(boundlist, remaining):
""" Checks if constant vector bounds matches the array one
"""
lineno = p.lineno(8)
if not boundlist: # Returns on empty list
if not isinstance(remaining, list):
return True # It's OK :-)
syntax_error(lineno, 'Unexpected extra vector dimensions. It should be %i' % len(remaining))
if not isinstance(remaining, list):
syntax_error(lineno, 'Mismatched vector size. Missing %i extra dimension(s)' % len(boundlist))
return False
if len(remaining) != boundlist[0].count:
syntax_error(lineno, 'Mismatched vector size. Expected %i elements, got %i.' % (boundlist[0].count,
len(remaining)))
return False # It's wrong. :-(
for row in remaining:
if not check_bound(boundlist[1:], row):
return False
return True
if p[8] is None:
p[0] = None
return
if check_bound(p[4].children, p[8]):
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4], default_value=p[8])
p[0] = None | python | def p_arr_decl_initialized(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector
"""
def check_bound(boundlist, remaining):
""" Checks if constant vector bounds matches the array one
"""
lineno = p.lineno(8)
if not boundlist: # Returns on empty list
if not isinstance(remaining, list):
return True # It's OK :-)
syntax_error(lineno, 'Unexpected extra vector dimensions. It should be %i' % len(remaining))
if not isinstance(remaining, list):
syntax_error(lineno, 'Mismatched vector size. Missing %i extra dimension(s)' % len(boundlist))
return False
if len(remaining) != boundlist[0].count:
syntax_error(lineno, 'Mismatched vector size. Expected %i elements, got %i.' % (boundlist[0].count,
len(remaining)))
return False # It's wrong. :-(
for row in remaining:
if not check_bound(boundlist[1:], row):
return False
return True
if p[8] is None:
p[0] = None
return
if check_bound(p[4].children, p[8]):
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4], default_value=p[8])
p[0] = None | var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L727-L765 |
boriel/zxbasic | zxbparser.py | p_bound | def p_bound(p):
""" bound : expr
"""
p[0] = make_bound(make_number(OPTIONS.array_base.value,
lineno=p.lineno(1)), p[1], p.lexer.lineno) | python | def p_bound(p):
""" bound : expr
"""
p[0] = make_bound(make_number(OPTIONS.array_base.value,
lineno=p.lineno(1)), p[1], p.lexer.lineno) | bound : expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L780-L784 |
boriel/zxbasic | zxbparser.py | p_const_vector_elem_list | def p_const_vector_elem_list(p):
""" const_number_list : expr
"""
if p[1] is None:
return
if not is_static(p[1]):
if isinstance(p[1], symbols.UNARY):
tmp = make_constexpr(p.lineno(1), p[1])
else:
api.errmsg.syntax_error_not_constant(p.lexer.lineno)
p[0] = None
return
else:
tmp = p[1]
p[0] = [tmp] | python | def p_const_vector_elem_list(p):
""" const_number_list : expr
"""
if p[1] is None:
return
if not is_static(p[1]):
if isinstance(p[1], symbols.UNARY):
tmp = make_constexpr(p.lineno(1), p[1])
else:
api.errmsg.syntax_error_not_constant(p.lexer.lineno)
p[0] = None
return
else:
tmp = p[1]
p[0] = [tmp] | const_number_list : expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L800-L816 |
boriel/zxbasic | zxbparser.py | p_const_vector_elem_list_list | def p_const_vector_elem_list_list(p):
""" const_number_list : const_number_list COMMA expr
"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], symbols.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
api.errmsg.syntax_error_not_constant(p.lineno(2))
p[0] = None
return
else:
tmp = p[3]
if p[1] is not None:
p[1].append(tmp)
p[0] = p[1] | python | def p_const_vector_elem_list_list(p):
""" const_number_list : const_number_list COMMA expr
"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], symbols.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
api.errmsg.syntax_error_not_constant(p.lineno(2))
p[0] = None
return
else:
tmp = p[3]
if p[1] is not None:
p[1].append(tmp)
p[0] = p[1] | const_number_list : const_number_list COMMA expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L819-L837 |
boriel/zxbasic | zxbparser.py | p_const_vector_vector_list | def p_const_vector_vector_list(p):
""" const_vector_list : const_vector_list COMMA const_vector
"""
if len(p[3]) != len(p[1][0]):
syntax_error(p.lineno(2), 'All rows must have the same number of elements')
p[0] = None
return
p[0] = p[1] + [p[3]] | python | def p_const_vector_vector_list(p):
""" const_vector_list : const_vector_list COMMA const_vector
"""
if len(p[3]) != len(p[1][0]):
syntax_error(p.lineno(2), 'All rows must have the same number of elements')
p[0] = None
return
p[0] = p[1] + [p[3]] | const_vector_list : const_vector_list COMMA const_vector | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L846-L854 |
boriel/zxbasic | zxbparser.py | p_statement_border | def p_statement_border(p):
""" statement : BORDER expr
"""
p[0] = make_sentence('BORDER',
make_typecast(TYPE.ubyte, p[2], p.lineno(1))) | python | def p_statement_border(p):
""" statement : BORDER expr
"""
p[0] = make_sentence('BORDER',
make_typecast(TYPE.ubyte, p[2], p.lineno(1))) | statement : BORDER expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L863-L867 |
boriel/zxbasic | zxbparser.py | p_statement_plot | def p_statement_plot(p):
""" statement : PLOT expr COMMA expr
"""
p[0] = make_sentence('PLOT',
make_typecast(TYPE.ubyte, p[2], p.lineno(3)),
make_typecast(TYPE.ubyte, p[4], p.lineno(3))) | python | def p_statement_plot(p):
""" statement : PLOT expr COMMA expr
"""
p[0] = make_sentence('PLOT',
make_typecast(TYPE.ubyte, p[2], p.lineno(3)),
make_typecast(TYPE.ubyte, p[4], p.lineno(3))) | statement : PLOT expr COMMA expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L870-L875 |
boriel/zxbasic | zxbparser.py | p_statement_plot_attr | def p_statement_plot_attr(p):
""" statement : PLOT attr_list expr COMMA expr
"""
p[0] = make_sentence('PLOT',
make_typecast(TYPE.ubyte, p[3], p.lineno(4)),
make_typecast(TYPE.ubyte, p[5], p.lineno(4)), p[2]) | python | def p_statement_plot_attr(p):
""" statement : PLOT attr_list expr COMMA expr
"""
p[0] = make_sentence('PLOT',
make_typecast(TYPE.ubyte, p[3], p.lineno(4)),
make_typecast(TYPE.ubyte, p[5], p.lineno(4)), p[2]) | statement : PLOT attr_list expr COMMA expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L878-L883 |
boriel/zxbasic | zxbparser.py | p_statement_draw3 | def p_statement_draw3(p):
""" statement : DRAW expr COMMA expr COMMA expr
"""
p[0] = make_sentence('DRAW3',
make_typecast(TYPE.integer, p[2], p.lineno(3)),
make_typecast(TYPE.integer, p[4], p.lineno(5)),
make_typecast(TYPE.float_, p[6], p.lineno(5))) | python | def p_statement_draw3(p):
""" statement : DRAW expr COMMA expr COMMA expr
"""
p[0] = make_sentence('DRAW3',
make_typecast(TYPE.integer, p[2], p.lineno(3)),
make_typecast(TYPE.integer, p[4], p.lineno(5)),
make_typecast(TYPE.float_, p[6], p.lineno(5))) | statement : DRAW expr COMMA expr COMMA expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L886-L892 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.