code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .symbol_ import Symbol
from .bound import SymbolBOUND
class SymbolBOUNDLIST(Symbol):
""" Defines a bound list for an array
"""
def __init__(self, *bounds):
for bound in bounds:
assert isinstance(bound, SymbolBOUND)
super(SymbolBOUNDLIST, self).__init__(*bounds)
def __len__(self): # Number of bounds:
return len(self.children)
def __getitem__(self, key):
return self.children[key]
def __str__(self):
return '(%s)' % ', '.join(str(x) for x in self)
@classmethod
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
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/boundlist.py
|
boundlist.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .block import SymbolBLOCK
class SymbolNOP(SymbolBLOCK):
def __init__(self):
super(SymbolNOP, self).__init__()
def __bool__(self):
return False
def __nonzero__(self):
return self.__bool__()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/nop.py
|
nop.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from api.constants import CLASS
from api.constants import SCOPE
from api.config import OPTIONS
import api.global_ as gl
from .type_ import SymbolBASICTYPE as BasicType
from .var import SymbolVAR
class SymbolPARAMDECL(SymbolVAR):
""" Defines a parameter declaration
"""
def __init__(self, varname, lineno, type_=None):
super(SymbolPARAMDECL, self).__init__(varname, lineno, type_=type_, class_=CLASS.var)
self.byref = OPTIONS.byref.value # By default all params By value (false)
self.offset = None # Set by PARAMLIST, contains positive offset from top of the stack
self.scope = SCOPE.parameter
@property
def size(self):
if self.byref:
return BasicType(gl.PTR_TYPE).size
if self.type_ is None:
return 0
return self.type_.size + (self.type_.size % gl.PARAM_ALIGN) # Make it even-sized (Float and Byte)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/paramdecl.py
|
paramdecl.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .symbol_ import Symbol
class SymbolPARAMLIST(Symbol):
""" Defines a list of parameters definitions in a function header
"""
def __init__(self, *params):
super(SymbolPARAMLIST, self).__init__(*params)
self.size = 0
def __getitem__(self, key):
return self.children[key]
def __setitem__(self, key, value):
self.children[key] = value
def __len__(self):
return len(self.children)
@classmethod
def make_node(cls, node, *params):
""" This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL instances
"""
if node is None:
node = cls()
if node.token != 'PARAMLIST':
return cls.make_node(None, node, *params)
for i in params:
if i is not None:
node.appendChild(i)
return node
def appendChild(self, param):
""" Overrides base class.
"""
Symbol.appendChild(self, param)
if param.offset is None:
param.offset = self.size
self.size += param.size
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/paramlist.py
|
paramlist.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from api.constants import CLASS
from .symbol_ import Symbol
from .type_ import Type
class SymbolSTRING(Symbol):
""" Defines a string constant.
"""
def __init__(self, value, lineno):
assert isinstance(value, str) or isinstance(value, SymbolSTRING)
super(SymbolSTRING, self).__init__()
self.value = value
self.type_ = Type.string
self.lineno = lineno
self.class_ = CLASS.const
self.t = value
@property
def t(self):
return self._t
@t.setter
def t(self, value):
assert isinstance(value, str)
self._t = value
def __str__(self):
return self.value
def __repr__(self):
return '"%s"' % str(self)
def __eq__(self, other):
if isinstance(other, str):
return self.value == other
assert isinstance(other, SymbolSTRING)
return self.value == other.value
def __gt__(self, other):
if isinstance(other, str):
return self.value > other
assert isinstance(other, SymbolSTRING)
return self.value > other.value
def __lt__(self, other):
if isinstance(other, str):
return self.value < other
assert isinstance(other, SymbolSTRING)
return self.value < other.value
def __hash__(self):
return id(self)
def __ne__(self, other):
return not self.__eq__(other)
def __ge__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return not self.__gt__(other)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/string_.py
|
string_.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .symbol_ import Symbol
from .number import SymbolNUMBER
from .string_ import SymbolSTRING
from .typecast import SymbolTYPECAST
from .type_ import SymbolTYPE
from .type_ import Type as TYPE
from api.check import is_number
from api.check import is_string
class SymbolUNARY(Symbol):
""" Defines an UNARY EXPRESSION e.g. (a + b)
Only the operator (e.g. 'PLUS') is stored.
"""
def __init__(self, oper, operand, lineno, type_=None):
super(SymbolUNARY, self).__init__(operand)
self.lineno = lineno
self.operator = oper
self._type = type_
@property
def type_(self):
if self._type is not None:
return self._type
return self.operand.type_
@property
def size(self):
""" sizeof(type)
"""
if self.type_ is None:
return 0
return self.type_.size
@property
def operand(self):
return self.children[0]
@operand.setter
def operand(self, value):
self.children[0] = value
def __str__(self):
return '%s(%s)' % (self.operator, self.operand)
def __repr__(self):
return '(%s: %s)' % (self.operator, self.operand)
@classmethod
def make_node(cls, lineno, operator, operand, func=None, type_=None):
""" Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: lambda 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'
"""
assert type_ is None or isinstance(type_, SymbolTYPE)
if func is not None: # Try constant-folding
if is_number(operand): # e.g. ABS(-5)
return SymbolNUMBER(func(operand.value), lineno=lineno)
elif is_string(operand): # e.g. LEN("a")
return SymbolSTRING(func(operand.text), lineno=lineno)
if type_ is None:
type_ = operand.type_
if operator == 'MINUS':
if not type_.is_signed:
type_ = type_.to_signed()
operand = SymbolTYPECAST.make_node(type_, operand, lineno)
elif operator == 'NOT':
type_ = TYPE.ubyte
return cls(operator, operand, lineno, type_)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/unary.py
|
unary.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import re
from collections import Counter
from ast_ import Ast
import api.global_
class Symbol(Ast):
""" Symbol object to store everything related to a symbol.
"""
def __init__(self, *children):
super(Symbol, self).__init__()
self._t = None
for child in children:
assert isinstance(child, Symbol)
self.appendChild(child)
self._required_by: Counter = Counter() # Symbols that depends on this one
self._requires: Counter = Counter() # Symbols this one depends on
@property
def required_by(self) -> Counter:
return self._required_by
@property
def requires(self) -> Counter:
return Counter(self._requires)
def mark_as_required_by(self, other: 'Symbol'):
if self is other:
return
self._required_by.update([other])
other._requires.update([self])
for sym in other.required_by:
sym.add_required_symbol(self)
def add_required_symbol(self, other: 'Symbol'):
if self is other:
return
self._requires.update([other])
other._required_by.update([self])
for sym in other.requires:
sym.mark_as_required_by(self)
@property
def token(self):
""" token = AST Symbol class name, removing the 'Symbol' prefix.
"""
return self.__class__.__name__[6:] # e.g. 'CALL', 'NUMBER', etc...
def __str__(self):
return self.token
def __repr__(self):
return str(self)
@property
def t(self):
if self._t is None:
self._t = api.global_.optemps.new_t()
return self._t
def copy_attr(self, other):
""" Copies all other attributes (not methods)
from the other object to this instance.
"""
if not isinstance(other, Symbol):
return # Nothing done if not a Symbol object
tmp = re.compile('__.*__')
for attr in (x for x in dir(other) if not tmp.match(x)):
if (
hasattr(self.__class__, attr) and
str(type(getattr(self.__class__, attr)) in ('property', 'function', 'instancemethod'))
):
continue
val = getattr(other, attr)
if isinstance(val, str) or str(val)[0] != '<': # Not a value
setattr(self, attr, val)
@property
def is_needed(self) -> bool:
return len(self.required_by) > 0
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/symbol_.py
|
symbol_.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License v3
# ----------------------------------------------------------------------
from .symbol_ import Symbol
class SymbolSENTENCE(Symbol):
""" Defines a BASIC SENTENCE object. e.g. 'BORDER'.
"""
def __init__(self, keyword, *args, **kwargs):
""" keyword = 'BORDER', or 'PRINT'
"""
assert not kwargs or 'lineno' in kwargs
super(SymbolSENTENCE, self).__init__(*(x for x in args if x is not None))
self.keyword = keyword
self.lineno = kwargs.get('lineno', None)
@property
def args(self):
return self.children
@property
def token(self):
""" Sentence takes it's token from the keyword not from it's name
"""
return self.keyword
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/sentence.py
|
sentence.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import functools
import api.global_ as gl
from api.constants import TYPE
from api.constants import CLASS
from api.constants import SCOPE
from .var import SymbolVAR
from .boundlist import SymbolBOUNDLIST
class SymbolVARARRAY(SymbolVAR):
""" This class expands VAR top denote Array Variables
"""
lbound_used = False # True if LBound has been used on this array
ubound_used = False # True if UBound has been used on this array
def __init__(self, varname, bounds, lineno, offset=None, type_=None):
super(SymbolVARARRAY, self).__init__(varname, lineno, offset=offset, type_=type_, class_=CLASS.array)
self.bounds = bounds
@property
def bounds(self):
return self.children[0]
@bounds.setter
def bounds(self, value):
assert isinstance(value, SymbolBOUNDLIST)
self.children = [value]
@property
def count(self):
""" Total number of array cells
"""
return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
@property
def size(self):
return self.count * self.type_.size if self.scope != SCOPE.parameter else TYPE.size(gl.PTR_TYPE)
@property
def memsize(self):
""" Total array cell + indexes size
"""
return (2 + (2 if self.lbound_used or self.ubound_used else 0)) * TYPE.size(gl.PTR_TYPE)
@property
def data_label(self):
return '{}.{}'.format(self.mangled, gl.ARRAY_DATA_PREFIX)
@property
def data_ptr_label(self):
return '{}.{}'.format(self.data_label, '__PTR__')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/vararray.py
|
vararray.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License v3
# ----------------------------------------------------------------------
from api.check import is_null
from .symbol_ import Symbol
class SymbolBLOCK(Symbol):
""" Defines a block of code.
"""
def __init__(self, *nodes):
super(SymbolBLOCK, self).__init__(*(x for x in nodes if not is_null(x)))
@classmethod
def make_node(cls, *args):
""" Creates a chain of code blocks.
"""
new_args = []
args = [x for x in args if not is_null(x)]
for x in args:
assert isinstance(x, Symbol)
if x.token == 'BLOCK':
new_args.extend(SymbolBLOCK.make_node(*x.children).children)
else:
new_args.append(x)
result = SymbolBLOCK(*new_args)
return result
def __getitem__(self, item):
return self.children[item]
def __len__(self):
return len(self.children)
def __eq__(self, other):
if not isinstance(other, SymbolBLOCK):
return False
return len(self) == len(other) and all([x == y for x, y in zip(self, other)])
def __hash__(self):
return id(self)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/block.py
|
block.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import api.global_ as gl
from api.errmsg import error
from api.errmsg import warning
from api.check import is_number
from api.check import is_const
from api.constants import SCOPE
from .call import SymbolCALL
from .number import SymbolNUMBER as NUMBER
from .typecast import SymbolTYPECAST as TYPECAST
from .binary import SymbolBINARY as BINARY
from .vararray import SymbolVARARRAY
from .arglist import SymbolARGLIST
class SymbolARRAYACCESS(SymbolCALL):
""" Defines an array access. It's pretty much like a function call
(e.g. A(1, 2) could be an array access or a function call, depending on
context). So we derive this class from SymbolCall
Initializing this with SymbolARRAYACCESS(symbol, ARRAYLOAD) will
make the returned expression to be loaded into the stack (by default
it only returns the pointer address to the element).
Parameters:
entry will be the symbol table entry.
Arglist a SymbolARGLIST instance.
"""
def __init__(self, entry, arglist, lineno):
super(SymbolARRAYACCESS, self).__init__(entry, arglist, lineno)
assert all(gl.BOUND_TYPE == x.type_.type_ for x in arglist), "Invalid type for array index"
@property
def entry(self):
return self.children[0]
@entry.setter
def entry(self, value):
assert isinstance(value, SymbolVARARRAY)
if self.children is None or not self.children:
self.children = [value]
else:
self.children[0] = value
@property
def type_(self):
return self.entry.type_
@property
def arglist(self):
return self.children[1]
@arglist.setter
def arglist(self, value):
assert isinstance(value, SymbolARGLIST)
self.children[1] = value
@property
def scope(self):
return self.entry.scope
@property
def offset(self):
""" If this is a constant access (e.g. A(1))
return the offset in bytes from the beginning of the
variable in memory.
Otherwise, if it's not constant (e.g. A(i))
returns None
"""
if self.scope == SCOPE.parameter:
return None
offset = 0
# Now we must typecast each argument to a u16 (POINTER) type
# i is the dimension ith index, b is the bound
for i, b in zip(self.arglist, self.entry.bounds):
tmp = i.children[0]
if is_number(tmp) or is_const(tmp):
if offset is not None:
offset = offset * b.count + tmp.value
else:
offset = None
break
if offset is not None:
offset *= self.type_.size
return offset
@classmethod
def make_node(cls, id_, arglist, lineno):
""" Creates an array access. A(x1, x2, ..., xn)
"""
assert isinstance(arglist, SymbolARGLIST)
variable = gl.SYMBOL_TABLE.access_array(id_, lineno)
if variable is None:
return None
if variable.scope != SCOPE.parameter:
if len(variable.bounds) != len(arglist):
error(lineno, "Array '%s' has %i dimensions, not %i" %
(variable.name, len(variable.bounds), len(arglist)))
return None
# Checks for array subscript range if the subscript is constant
# e.g. A(1) is a constant subscript access
btype = gl.SYMBOL_TABLE.basic_types[gl.BOUND_TYPE]
for i, b in zip(arglist, variable.bounds):
lower_bound = NUMBER(b.lower, type_=btype, lineno=lineno)
if is_number(i.value) or is_const(i.value):
val = i.value.value
if val < b.lower or val > b.upper:
warning(lineno, "Array '%s' subscript out of range" % id_)
i.value = BINARY.make_node('MINUS',
TYPECAST.make_node(btype, i.value, lineno),
lower_bound, lineno, func=lambda x, y: x - y,
type_=btype)
else:
btype = gl.SYMBOL_TABLE.basic_types[gl.BOUND_TYPE]
for arg in arglist:
arg.value = TYPECAST.make_node(btype, arg.value, arg.value.lineno)
# Returns the variable entry and the node
return cls(variable, arglist, lineno)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/arrayaccess.py
|
arrayaccess.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .symbol_ import Symbol
from .number import SymbolNUMBER
from .var import SymbolVAR
from api.check import is_static
from api.errmsg import error
class SymbolBOUND(Symbol):
""" Defines an array bound.
Eg.:
DIM a(1 TO 10, 3 TO 5, 8) defines 3 bounds,
1..10, 3..5, and 0..8
"""
def __init__(self, lower, upper):
if isinstance(lower, SymbolNUMBER):
lower = lower.value
if isinstance(upper, SymbolNUMBER):
upper = upper.value
assert isinstance(lower, int)
assert isinstance(upper, int)
assert upper >= lower >= 0
super(SymbolBOUND, self).__init__()
self.lower = lower
self.upper = upper
@property
def count(self):
return self.upper - self.lower + 1
@staticmethod
def make_node(lower, upper, lineno):
""" Creates an array bound
"""
if not is_static(lower, upper):
error(lineno, 'Array bounds must be constants')
return None
if isinstance(lower, SymbolVAR):
lower = lower.value
if lower is None: # semantic error
error(lineno, "Unknown lower bound for array dimension")
return
if isinstance(upper, SymbolVAR):
upper = upper.value
if upper is None: # semantic error
error(lineno, "Unknown upper bound for array dimension")
return
lower.value = int(lower.value)
upper.value = int(upper.value)
if lower.value < 0:
error(lineno, 'Array bounds must be greater than 0')
return None
if lower.value > upper.value:
error(lineno, 'Lower array bound must be less or equal to upper one')
return None
return SymbolBOUND(lower.value, upper.value)
def __str__(self):
if self.lower == 0:
return '({})'.format(self.upper)
return '({} TO {})'.format(self.lower, self.upper)
def __repr__(self):
return self.token + str(self)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/bound.py
|
bound.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from api import global_
from api.config import OPTIONS
from api.constants import SCOPE
from api.constants import KIND
from api.constants import CLASS
from .symbol_ import Symbol
from .type_ import SymbolTYPE
# ----------------------------------------------------------------------
# IDentifier Symbol object
# ----------------------------------------------------------------------
class SymbolVAR(Symbol):
""" Defines an VAR (Variable) symbol.
These class and their children classes are also stored in the symbol
table as table entries to store variable data
"""
def __init__(self, varname, lineno, offset=None, type_=None, class_=None):
super(SymbolVAR, self).__init__()
self.name = varname
self.filename = global_.FILENAME # In which file was first used
self.lineno = lineno # In which line was first used
self.class_ = class_ # variable "class": var, label, function, etc.
self.mangled = '%s%s' % (global_.MANGLE_CHR, varname) # This value will be overridden later
self.declared = False # if explicitly declared (DIM var AS <type>)
self.type_ = type_ # if None => unknown type (yet)
self.offset = offset # If local variable or parameter, +/- offset from top of the stack
self.default_value = None # If defined, variable will be initialized with this value (Arrays = List of Bytes)
self.scope = SCOPE.global_ # One of 'global', 'parameter', 'local'
self.byref = False # By default, it's a global var
self.__kind = KIND.var # If not None, it should be one of 'function' or 'sub'
self.addr = None # If not None, the address of this symbol (string)
self.alias = None # If not None, this var is an alias of another
self.aliased_by = [] # Which variables are an alias of this one
self._accessed = False # Where this object has been accessed (if false it might be not compiled)
self.caseins = OPTIONS.case_insensitive.value # Whether this ID is case insensitive or not
self._t = global_.optemps.new_t()
self.scopeRef = None # Must be set by the Symbol Table. PTR to the scope
self.callable = None # For functions, subs, arrays and strings this will be True
@property
def size(self):
if self.type_ is None:
return 0
return self.type_.size
@property
def kind(self):
return self.__kind
def set_kind(self, value, lineno):
assert KIND.is_valid(value)
self.__kind = value
@property
def byref(self):
return self.__byref
@byref.setter
def byref(self, value):
assert isinstance(value, bool)
self.__byref = value
def add_alias(self, entry):
""" Adds id to the current list 'aliased_by'
"""
assert isinstance(entry, SymbolVAR)
self.aliased_by.append(entry)
def make_alias(self, entry):
""" Make this variable an alias of another one
"""
entry.add_alias(self)
self.alias = entry
self.scope = entry.scope # Local aliases can be "global" (static)
self.byref = entry.byref
self.offset = entry.offset
self.addr = entry.addr
@property
def is_aliased(self):
""" Return if this symbol is aliased by another
"""
return len(self.aliased_by) > 0
def __str__(self):
return self.name
def __repr__(self):
return "ID:%s" % str(self)
@property
def t(self):
# HINT: Parameters and local variables must have it's .t member as '$name'
if self.class_ == CLASS.const:
return str(self.value)
if self.scope == SCOPE.global_:
if self.class_ == CLASS.array:
return self.data_label
else:
return self.mangled
if self.type_ is None or not self.type_.is_dynamic:
return self._t
return '$' + self._t # Local string variables (and parameters) use '$' (see backend)
@property
def type_(self):
return self._type
@type_.setter
def type_(self, value):
assert (value is None) or isinstance(value, SymbolTYPE)
self._type = value
@staticmethod
def to_label(var_instance):
""" Converts a var_instance to a label one
"""
# This can be done 'cause LABEL is just a dummy descent of VAR
assert isinstance(var_instance, SymbolVAR)
from symbols import LABEL
var_instance.__class__ = LABEL
var_instance.class_ = CLASS.label
var_instance._scope_owner = []
return var_instance
@staticmethod
def to_function(var_instance, lineno=None):
""" Converts a var_instance to a function one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance
@staticmethod
def to_vararray(var_instance, bounds):
""" Converts a var_instance to a var array one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import BOUNDLIST
from symbols import VARARRAY
assert isinstance(bounds, BOUNDLIST)
var_instance.__class__ = VARARRAY
var_instance.class_ = CLASS.array
var_instance.bounds = bounds
return var_instance
@property
def value(self):
""" An alias of default value, only available is class_ is CONST
"""
assert self.class_ == CLASS.const
if isinstance(self.default_value, SymbolVAR):
return self.default_value.value
return self.default_value
@value.setter
def value(self, val):
assert self.class_ == CLASS.const
self.default_value = val
@property
def accessed(self):
return self._accessed
@accessed.setter
def accessed(self, value):
self._accessed = bool(value)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/var.py
|
var.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .symbol_ import Symbol
class SymbolVARDECL(Symbol):
""" Defines a Variable declaration
"""
def __init__(self, entry):
""" The declared variable entry
"""
super(SymbolVARDECL, self).__init__(entry)
@property
def entry(self):
return self.children[0]
@property
def type_(self):
return self.entry.type_
@property
def mangled(self):
return self.entry.mangled
@property
def size(self):
return self.entry.size
@property
def default_value(self):
return self.entry.default_value
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/vardecl.py
|
vardecl.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from typing import Optional
from api.constants import CLASS
from api.constants import KIND
import api.errmsg
from .var import SymbolVAR
from .paramlist import SymbolPARAMLIST
from .block import SymbolBLOCK
class SymbolFUNCTION(SymbolVAR):
""" This class expands VAR top denote Function declarations
"""
def __init__(self, varname, lineno, offset=None, type_=None):
super(SymbolFUNCTION, self).__init__(varname, lineno, offset, class_=CLASS.function, type_=type_)
self.reset()
def reset(self, lineno=None, offset=None, type_=None):
""" This is called when we need to reinitialize the instance state
"""
self.lineno = self.lineno if lineno is None else lineno
self.type_ = self.type_ if type_ is None else type_
self.offset = self.offset if offset is None else offset
self.callable = True
self.params = SymbolPARAMLIST()
self.body = SymbolBLOCK()
self.__kind = KIND.unknown
self.local_symbol_table = None
@property
def kind(self):
return self.__kind
def set_kind(self, value, lineno):
assert KIND.is_valid(value)
if self.__kind != KIND.unknown and self.__kind != value:
q = KIND.to_string(KIND.sub) if self.__kind == KIND.function else KIND.to_string(KIND.function)
api.errmsg.error(lineno, "'%s' is a %s, not a %s" %
(self.name, KIND.to_string(self.__kind).upper(), q.upper()))
self.__kind = value
@property
def params(self) -> SymbolPARAMLIST:
if not self.children:
return SymbolPARAMLIST()
return self.children[0]
@params.setter
def params(self, value: SymbolPARAMLIST):
assert isinstance(value, SymbolPARAMLIST)
if self.children is None:
self.children = []
if self.children:
self.children[0] = value
else:
self.children = [value]
@property
def body(self) -> SymbolBLOCK:
if not self.children or len(self.children) < 2:
self.body = SymbolBLOCK()
return self.children[1]
@body.setter
def body(self, value: Optional[SymbolBLOCK]):
if value is None:
value = SymbolBLOCK()
assert isinstance(value, SymbolBLOCK)
if self.children is None:
self.children = []
if not self.children:
self.params = SymbolPARAMLIST()
if len(self.children) < 2:
self.children.append(value)
else:
self.children[1] = value
def __repr__(self):
return 'FUNC:{}'.format(self.name)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/function.py
|
function.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
# ---- AST Symbols ----
from .symbol_ import Symbol as SYMBOL
from .arglist import SymbolARGLIST as ARGLIST
from .argument import SymbolARGUMENT as ARGUMENT
from .arrayaccess import SymbolARRAYACCESS as ARRAYACCESS
from .arraydecl import SymbolARRAYDECL as ARRAYDECL
from .arrayload import SymbolARRAYLOAD as ARRAYLOAD
from .asm import SymbolASM as ASM
from .binary import SymbolBINARY as BINARY
from .block import SymbolBLOCK as BLOCK
from .bound import SymbolBOUND as BOUND
from .boundlist import SymbolBOUNDLIST as BOUNDLIST
from .builtin import SymbolBUILTIN as BUILTIN
from .call import SymbolCALL as CALL
from .const import SymbolCONST as CONST
from .funccall import SymbolFUNCCALL as FUNCCALL
from .funcdecl import SymbolFUNCDECL as FUNCDECL
from .function import SymbolFUNCTION as FUNCTION
from .nop import SymbolNOP as NOP
from .number import SymbolNUMBER as NUMBER
from .paramdecl import SymbolPARAMDECL as PARAMDECL
from .paramlist import SymbolPARAMLIST as PARAMLIST
from .sentence import SymbolSENTENCE as SENTENCE
from .string_ import SymbolSTRING as STRING
from .strslice import SymbolSTRSLICE as STRSLICE
from .type_ import SymbolBASICTYPE as BASICTYPE
from .type_ import SymbolTYPE as TYPE
from .type_ import SymbolTYPEREF as TYPEREF
from .typecast import SymbolTYPECAST as TYPECAST
from .unary import SymbolUNARY as UNARY
from .var import SymbolVAR as VAR
from .vararray import SymbolVARARRAY as VARARRAY
from .vardecl import SymbolVARDECL as VARDECL
from .label import SymbolLABEL as LABEL
__all__ = [
'ARGLIST',
'ARGUMENT',
'ARRAYACCESS',
'ARRAYDECL',
'ARRAYLOAD',
'ASM',
'BASICTYPE',
'BINARY',
'BLOCK',
'BOUND',
'BOUNDLIST',
'BUILTIN',
'CALL',
'CONST',
'FUNCCALL',
'FUNCDECL',
'FUNCTION',
'LABEL',
'NOP',
'NUMBER',
'PARAMDECL',
'PARAMLIST',
'SENTENCE',
'STRING',
'STRSLICE',
'SYMBOL',
'TYPE',
'TYPEREF',
'TYPECAST',
'UNARY',
'VAR',
'VARARRAY',
'VARDECL',
]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/symbols/__init__.py
|
__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:et:
# Simple debugging module
import os
import inspect
from .config import OPTIONS
__all__ = ['__DEBUG__', '__LINE__', '__FILE__']
# --------------------- END OF GLOBAL FLAGS ---------------------
def __DEBUG__(msg, level=1):
if level > OPTIONS.Debug.value:
return
line = inspect.getouterframes(inspect.currentframe())[1][2]
fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])
OPTIONS.stderr.value.write('debug: %s:%i %s\n' % (fname, line, msg))
def __LINE__():
""" Returns current file interpreter line
"""
return inspect.getouterframes(inspect.currentframe())[1][2]
def __FILE__():
""" Returns current file interpreter line
"""
return inspect.currentframe().f_code.co_filename
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/debug.py
|
debug.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import os
from .decorator import classproperty
# -------------------------------------------------
# Global constants
# -------------------------------------------------
# Path to main ZX Basic compiler executable
ZXBASIC_ROOT = os.path.abspath(os.path.join(
os.path.abspath(os.path.dirname(os.path.abspath(__file__))), os.path.pardir)
)
# ----------------------------------------------------------------------
# Class enums
# ----------------------------------------------------------------------
class CLASS(object):
""" Enums class constants
"""
unknown = 'unknown' # 0
var = 'var' # 1 # scalar variable
array = 'array' # 2 # array variable
function = 'function' # 3 # function
label = 'label' # 4 Labels
const = 'const' # 5 # constant literal value e.g. 5 or "AB"
sub = 'sub' # 6 # subroutine
type_ = 'type' # 7 # type
_CLASS_NAMES = {
unknown: '(unknown)',
var: 'var',
array: 'array',
function: 'function',
label: 'label',
const: 'const',
sub: 'sub',
type_: 'type'
}
@classproperty
def classes(cls):
return (cls.unknown, cls.var, cls.array, cls.function, cls.sub,
cls.const, cls.label)
@classmethod
def is_valid(cls, class_):
""" Whether the given class is
valid or not.
"""
return class_ in cls.classes
@classmethod
def to_string(cls, class_):
assert cls.is_valid(class_)
return cls._CLASS_NAMES[class_]
class ARRAY(object):
""" Enums array constants
"""
bound_size = 2 # This might change depending on arch, program, etc..
bound_count = 2 # Size of bounds counter
array_type_size = 1 # Size of array type
class TYPE(object):
""" Enums type constants
"""
auto = unknown = None
byte_ = 1
ubyte = 2
integer = 3
uinteger = 4
long_ = 5
ulong = 6
fixed = 7
float_ = 8
string = 9
TYPE_SIZES = {
byte_: 1, ubyte: 1,
integer: 2, uinteger: 2,
long_: 4, ulong: 4,
fixed: 4, float_: 5,
string: 2, unknown: 0
}
TYPE_NAMES = {
byte_: 'byte', ubyte: 'ubyte',
integer: 'integer', uinteger: 'uinteger',
long_: 'long', ulong: 'ulong',
fixed: 'fixed', float_: 'float',
string: 'string', unknown: 'none'
}
@classproperty
def types(cls):
return tuple(cls.TYPE_SIZES.keys())
@classmethod
def size(cls, type_):
return cls.TYPE_SIZES.get(type_, None)
@classproperty
def integral(cls):
return (cls.byte_, cls.ubyte, cls.integer, cls.uinteger,
cls.long_, cls.ulong)
@classproperty
def signed(cls):
return (cls.byte_, cls.integer, cls.long_, cls.fixed, cls.float_)
@classproperty
def unsigned(cls):
return (cls.ubyte, cls.uinteger, cls.ulong)
@classproperty
def decimals(cls):
return (cls.fixed, cls.float_)
@classproperty
def numbers(cls):
return tuple(list(cls.integral) + list(cls.decimals))
@classmethod
def is_valid(cls, type_):
""" Whether the given type is
valid or not.
"""
return type_ in cls.types
@classmethod
def is_signed(cls, type_):
return type_ in cls.signed
@classmethod
def is_unsigned(cls, type_):
return type_ in cls.unsigned
@classmethod
def to_signed(cls, type_):
""" Return signed type or equivalent
"""
if type_ in cls.unsigned:
return {TYPE.ubyte: TYPE.byte_,
TYPE.uinteger: TYPE.integer,
TYPE.ulong: TYPE.long_}[type_]
if type_ in cls.decimals or type_ in cls.signed:
return type_
return cls.unknown
@classmethod
def to_string(cls, type_):
""" Return ID representation (string) of a type
"""
return cls.TYPE_NAMES[type_]
@classmethod
def to_type(cls, typename):
""" Converts a type ID to name. On error returns None
"""
NAME_TYPES = {cls.TYPE_NAMES[x]: x for x in cls.TYPE_NAMES}
return NAME_TYPES.get(typename, None)
class SCOPE(object):
""" Enum scopes
"""
unknown = None
global_ = 'global'
local = 'local'
parameter = 'parameter'
_names = {
unknown: 'unknown',
global_: 'global',
local: 'local',
parameter: 'parameter'
}
@classmethod
def is_valid(cls, scope):
return cls._names.get(scope, None) is not None
@classmethod
def to_string(cls, scope):
assert cls.is_valid(scope)
return cls._names[scope]
class KIND(object):
""" Enum kind
"""
unknown = None
var = 'var'
function = 'function'
sub = 'sub'
type_ = 'type'
_NAMES = {
unknown: '(unknown)',
var: 'variable',
function: 'function',
sub: 'subroutine',
type_: 'type'
}
@classmethod
def is_valid(cls, kind):
return cls._NAMES.get(kind, None) is not None
@classmethod
def to_string(cls, kind):
assert cls.is_valid(kind)
return cls._NAMES.get(kind)
class CONVENTION(object):
unknown = None
fastcall = '__fastcall__'
stdcall = '__stdcall__'
_NAMES = {
unknown: '(unknown)',
fastcall: '__fastcall__',
stdcall: '__stdcall__'
}
@classmethod
def is_valid(cls, convention):
return cls._NAMES.get(convention, None) is not None
@classmethod
def to_string(cls, convention):
assert cls.is_valid(convention)
return cls._NAMES[convention]
# ----------------------------------------------------------------------
# Identifier Class (variable, function, label, array)
# ----------------------------------------------------------------------
ID_CLASSES = CLASS.classes
# ----------------------------------------------------------------------
# Deprecated suffixes for variable names, such as "a$"
# ----------------------------------------------------------------------
DEPRECATED_SUFFIXES = ('$', '%', '&')
# ----------------------------------------------------------------------
# Identifier type
# i8 = Integer, 8 bits
# u8 = Unsigned, 8 bits and so on
# ----------------------------------------------------------------------
ID_TYPES = TYPE.types
# Maps deprecated suffixes to types
SUFFIX_TYPE = {'$': TYPE.string, '%': TYPE.integer, '&': TYPE.long_}
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/constants.py
|
constants.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:et:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from . import config
from . import global_
from .constants import CLASS
from .constants import SCOPE
import api.errmsg
from .errmsg import error
__all__ = ['check_type',
'check_is_declared_explicit',
'check_type_is_explicit',
'check_call_arguments',
'check_pending_calls',
'check_pending_labels',
'is_number',
'is_const',
'is_static',
'is_string',
'is_numeric',
'is_dynamic',
'is_null',
'is_unsigned',
'common_type'
]
# ----------------------------------------------------------------------
# Several check functions.
# These functions trigger syntax errors if checking goal fails.
# ----------------------------------------------------------------------
def check_type(lineno, type_list, arg):
""" Check arg's type is one in type_list, otherwise,
raises an error.
"""
if not isinstance(type_list, list):
type_list = [type_list]
if arg.type_ in type_list:
return True
if len(type_list) == 1:
error(lineno, "Wrong expression type '%s'. Expected '%s'" %
(arg.type_, type_list[0]))
else:
error(lineno, "Wrong expression type '%s'. Expected one of '%s'"
% (arg.type_, tuple(type_list)))
return False
def check_is_declared_explicit(lineno, id_, classname='variable'):
""" Check if the current ID is already declared.
If not, triggers a "undeclared identifier" error,
if the --explicit command line flag is enabled (or #pragma
option strict is in use).
If not in strict mode, passes it silently.
"""
if not config.OPTIONS.explicit.value:
return True
entry = global_.SYMBOL_TABLE.check_is_declared(id_, lineno, classname)
return entry is not None # True if declared
def check_type_is_explicit(lineno: int, id_: str, type_):
from symbols.type_ import SymbolTYPE
assert isinstance(type_, SymbolTYPE)
if type_.implicit:
if config.OPTIONS.strict.value:
api.errmsg.syntax_error_undeclared_type(lineno, id_)
def check_call_arguments(lineno, id_, args):
""" Check arguments against function signature.
Checks every argument in a function call against a function.
Returns True on success.
"""
if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'):
return False
if not global_.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno):
return False
entry = global_.SYMBOL_TABLE.get_entry(id_)
if len(args) != len(entry.params):
c = 's' if len(entry.params) != 1 else ''
error(lineno, "Function '%s' takes %i parameter%s, not %i" %
(id_, len(entry.params), c, len(args)))
return False
for arg, param in zip(args, entry.params):
if arg.class_ in (CLASS.var, CLASS.array) and param.class_ != arg.class_:
error(lineno, "Invalid argument '{}'".format(arg.value))
return None
if not arg.typecast(param.type_):
return False
if param.byref:
from symbols.var import SymbolVAR
if not isinstance(arg.value, SymbolVAR):
error(lineno, "Expected a variable name, not an expression (parameter By Reference)")
return False
if arg.class_ not in (CLASS.var, CLASS.array):
error(lineno, "Expected a variable or array name (parameter By Reference)")
return False
arg.byref = True
if arg.value is not None:
arg.value.add_required_symbol(param)
if entry.forwarded: # The function / sub was DECLARED but not implemented
error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name))
return False
return True
def check_pending_calls():
""" Calls the above function for each pending call of the current scope
level
"""
result = True
# Check for functions defined after calls (parameters, etc)
for id_, params, lineno in global_.FUNCTION_CALLS:
result = result and check_call_arguments(lineno, id_, params)
return result
def check_pending_labels(ast):
""" Iteratively traverses the node looking for ID with no class set,
marks them as labels, and check they've been declared.
This way we avoid stack overflow for high line-numbered listings.
"""
result = True
visited = set()
pending = [ast]
while pending:
node = pending.pop()
if node is None or node in visited: # Avoid recursive infinite-loop
continue
visited.add(node)
for x in node.children:
pending.append(x)
if node.token != 'VAR' or (node.token == 'VAR' and node.class_ is not CLASS.unknown):
continue
tmp = global_.SYMBOL_TABLE.get_entry(node.name)
if tmp is None or tmp.class_ is CLASS.unknown:
error(node.lineno, 'Undeclared identifier "%s"'
% node.name)
else:
assert tmp.class_ == CLASS.label
node.to_label(node)
result = result and tmp is not None
return result
def check_and_make_label(lbl, lineno):
""" Checks if the given label (or line number) is valid and, if so,
returns a label object.
:param lbl: Line number of label (string)
:param lineno: Line number in the basic source code for error reporting
:return: Label object or None if error.
"""
if isinstance(lbl, float):
if lbl == int(lbl):
id_ = str(int(lbl))
else:
error(lineno, 'Line numbers must be integers.')
return None
else:
id_ = lbl
return global_.SYMBOL_TABLE.access_label(id_, lineno)
# ----------------------------------------------------------------------
# Function for checking some arguments
# ----------------------------------------------------------------------
def is_null(*symbols):
""" True if no nodes or all the given nodes are either
None, NOP or empty blocks. For blocks this applies recursively
"""
from symbols.symbol_ import Symbol
for sym in symbols:
if sym is None:
continue
if not isinstance(sym, Symbol):
return False
if sym.token == 'NOP':
continue
if sym.token == 'BLOCK':
if not is_null(*sym.children):
return False
continue
return False
return True
def is_SYMBOL(token, *symbols):
""" Returns True if ALL of the given argument are AST nodes
of the given token (e.g. 'BINARY')
"""
from symbols.symbol_ import Symbol
assert all(isinstance(x, Symbol) for x in symbols)
for sym in symbols:
if sym.token != token:
return False
return True
def is_LABEL(*p):
return is_SYMBOL('LABEL', *p)
def is_string(*p):
return is_SYMBOL('STRING', *p)
def is_const(*p):
""" A constant in the program, like CONST a = 5
"""
return is_SYMBOL('VAR', *p) and all(x.class_ == CLASS.const for x in p)
def is_CONST(*p):
""" Not to be confused with the above.
Check it's a CONSTant expression
"""
return is_SYMBOL('CONST', *p)
def is_static(*p):
""" A static value (does not change at runtime)
which is known at compile time
"""
return all(is_CONST(x) or
is_number(x) or
is_const(x)
for x in p)
def is_number(*p):
""" Returns True if ALL of the arguments are AST nodes
containing NUMBER or numeric CONSTANTS
"""
try:
for i in p:
if i.token != 'NUMBER' and (i.token != 'ID' or i.class_ != CLASS.const):
return False
return True
except:
pass
return False
def is_var(*p):
""" Returns True if ALL of the arguments are AST nodes
containing ID
"""
return is_SYMBOL('VAR', *p)
def is_integer(*p):
from symbols.type_ import Type
try:
for i in p:
if not i.is_basic or not Type.is_integral(i.type_):
return False
return True
except:
pass
return False
def is_unsigned(*p):
""" Returns false unless all types in p are unsigned
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_unsigned(i.type_):
return False
return True
except:
pass
return False
def is_signed(*p):
""" Returns false unless all types in p are signed
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_signed(i.type_):
return False
return True
except:
pass
return False
def is_numeric(*p):
""" Returns false unless all elements in p are of numerical type
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_numeric(i.type_):
return False
return True
except:
pass
return False
def is_type(type_, *p):
""" True if all args have the same type
"""
try:
for i in p:
if i.type_ != type_:
return False
return True
except:
pass
return False
def is_dynamic(*p): # TODO: Explain this better
""" True if all args are dynamic (e.g. Strings, dynamic arrays, etc)
The use a ptr (ref) and it might change during runtime.
"""
from symbols.type_ import Type
try:
for i in p:
if i.scope == SCOPE.global_ and i.is_basic and \
i.type_ != Type.string:
return False
return True
except:
pass
return False
def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p)
def is_block_accessed(block):
""" Returns True if a block is "accessed". A block of code is accessed if
it has a LABEL and it is used in a GOTO, GO SUB or @address access
:param block: A block of code (AST node)
:return: True / False depending if it has labels accessed or not
"""
if is_LABEL(block) and block.accessed:
return True
for child in block.children:
if not is_callable(child) and is_block_accessed(child):
return True
return False
def is_temporary_value(node) -> bool:
""" Returns if the AST node value is a variable or a temporary copy in the heap.
"""
return node.token not in ('STRING', 'VAR') and node.t[0] not in ('_', '#')
def common_type(a, b):
""" Returns a type which is common for both a and b types.
Returns None if no common types allowed.
"""
from symbols.type_ import SymbolBASICTYPE as BASICTYPE
from symbols.type_ import Type as TYPE
from symbols.type_ import SymbolTYPE
if a is None or b is None:
return None
if not isinstance(a, SymbolTYPE):
a = a.type_
if not isinstance(b, SymbolTYPE):
b = b.type_
if a == b: # Both types are the same?
return a # Returns it
if a == TYPE.unknown and b == TYPE.unknown:
return BASICTYPE(global_.DEFAULT_TYPE)
if a == TYPE.unknown:
return b
if b == TYPE.unknown:
return a
# TODO: This will removed / expanded in the future
assert a.is_basic
assert b.is_basic
types = (a, b)
if TYPE.float_ in types:
return TYPE.float_
if TYPE.fixed in types:
return TYPE.fixed
if TYPE.string in types: # TODO: Check this ??
return TYPE.unknown
result = a if a.size > b.size else b
if not TYPE.is_unsigned(a) or not TYPE.is_unsigned(b):
result = TYPE.to_signed(result)
return result
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/check.py
|
check.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import sys
from . import global_
from .config import OPTIONS
# Exports only these functions. Others
__all__ = ['error', 'warning']
def msg_output(msg):
if msg in global_.error_msg_cache:
return
OPTIONS.stderr.value.write("%s\n" % msg)
global_.error_msg_cache.add(msg)
def info(msg):
if OPTIONS.Debug.value < 1:
return
OPTIONS.stderr.value.write("info: %s\n" % msg)
def error(lineno, msg, fname=None):
""" Generic syntax error routine
"""
if fname is None:
fname = global_.FILENAME
if global_.has_errors > OPTIONS.max_syntax_errors.value:
msg = 'Too many errors. Giving up!'
msg = "%s:%i: error: %s" % (fname, lineno, msg)
msg_output(msg)
if global_.has_errors > OPTIONS.max_syntax_errors.value:
sys.exit(1)
global_.has_errors += 1
def warning(lineno, msg, fname=None):
""" Generic warning error routine
"""
if fname is None:
fname = global_.FILENAME
msg = "%s:%i: warning: %s" % (fname, lineno, msg)
msg_output(msg)
global_.has_warnings += 1
def warning_implicit_type(lineno, id_, type_=None):
""" Warning: Using default implicit type 'x'
"""
if OPTIONS.strict.value:
syntax_error_undeclared_type(lineno, id_)
return
if type_ is None:
type_ = global_.DEFAULT_TYPE
warning(lineno, "Using default implicit type '%s' for '%s'" % (type_, id_))
def warning_condition_is_always(lineno, cond=False):
""" Warning: Condition is always false/true
"""
warning(lineno, "Condition is always %s" % cond)
def warning_conversion_lose_digits(lineno):
""" Warning: Conversion may lose significant digits
"""
warning(lineno, 'Conversion may lose significant digits')
def warning_empty_loop(lineno):
""" Warning: Empty loop
"""
warning(lineno, 'Empty loop')
def warning_empty_if(lineno):
""" Warning: Useless empty IF ignored
"""
warning(lineno, 'Useless empty IF ignored')
# Emmits an optimization warning
def warning_not_used(lineno, id_, kind='Variable'):
if OPTIONS.optimization.value > 0:
warning(lineno, "%s '%s' is never used" % (kind, id_))
# ----------------------------------------
# Syntax error: Expected string instead of
# numeric expression.
# ----------------------------------------
def syntax_error_expected_string(lineno, _type):
error(lineno, "Expected a 'string' type expression, got '%s' instead" % _type)
# ----------------------------------------
# Syntax error: FOR variable should be X
# instead of Y
# ----------------------------------------
def syntax_error_wrong_for_var(lineno, x, y):
error(lineno, "FOR variable should be '%s' instead of '%s'" %
(x, y))
# ----------------------------------------
# Syntax error: Initializer expression is
# not constant
# ----------------------------------------
def syntax_error_not_constant(lineno):
error(lineno, "Initializer expression is not constant.")
# ----------------------------------------
# Syntax error: Id is neither an array nor
# a function
# ----------------------------------------
def syntax_error_not_array_nor_func(lineno, varname):
error(lineno, "'%s' is neither an array nor a function." % varname)
# ----------------------------------------
# Syntax error: Id is neither an array nor
# a function
# ----------------------------------------
def syntax_error_not_an_array(lineno, varname):
error(lineno, "'%s' is not an array (or has not been declared yet)" % varname)
# ----------------------------------------
# Syntax error: function redefinition type
# mismatch
# ----------------------------------------
def syntax_error_func_type_mismatch(lineno, entry):
error(lineno, "Function '%s' (previously declared at %i) type mismatch" % (entry.name, entry.lineno))
# ----------------------------------------
# Syntax error: function redefinition parm.
# mismatch
# ----------------------------------------
def syntax_error_parameter_mismatch(lineno, entry):
error(lineno, "Function '%s' (previously declared at %i) parameter mismatch" % (entry.name, entry.lineno))
# ----------------------------------------
# Syntax error: can't convert value to the
# given type.
# ----------------------------------------
def syntax_error_cant_convert_to_type(lineno, expr_str, type_):
error(lineno, "Cant convert '%s' to type %s" % (expr_str, type_))
# ----------------------------------------
# Syntax error: is a SUB not a FUNCTION
# ----------------------------------------
def syntax_error_is_a_sub_not_a_func(lineno, name):
error(lineno, "'%s' is SUBROUTINE not a FUNCTION" % name)
# ----------------------------------------
# Syntax error: strict mode: missing type declaration
# ----------------------------------------
def syntax_error_undeclared_type(lineno: int, id_: str):
error(lineno, "strict mode: missing type declaration for '%s'" % id_)
# ----------------------------------------
# Cannot assign a value to 'var'. It's not a variable
# ----------------------------------------
def syntax_error_cannot_assign_not_a_var(lineno, id_):
error(lineno, "Cannot assign a value to '%s'. It's not a variable" % id_)
# ----------------------------------------
# Cannot assign a value to 'var'. It's not a variable
# ----------------------------------------
def syntax_error_address_must_be_constant(lineno):
error(lineno, 'Address must be a numeric constant expression')
# ----------------------------------------
# Cannot pass an array by value
# ----------------------------------------
def syntax_error_cannot_pass_array_by_value(lineno, id_):
error(lineno, "Array parameter '%s' must be passed ByRef" % id_)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/errmsg.py
|
errmsg.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ast_ import NodeVisitor
from .config import OPTIONS
import api.errmsg
from api.errmsg import warning
import api.check as chk
from api.constants import TYPE, SCOPE, CLASS
import api.global_ as gl
import symbols
import types
from api.debug import __DEBUG__
from api.errmsg import warning_not_used
import api.utils
import api.symboltable
class ToVisit(object):
""" Used just to signal an object to be
traversed.
"""
def __init__(self, obj):
self.obj = obj
class OptimizerVisitor(NodeVisitor):
""" Implements some optimizations
"""
NOP = symbols.NOP() # Return this for "erased" nodes
@staticmethod
def TYPE(type_):
""" Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
"""
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid(type_)
return gl.SYMBOL_TABLE.basic_types[type_]
def visit(self, node):
if self.O_LEVEL < 1: # Optimize only if O1 or above
return node
stack = [ToVisit(node)]
last_result = None
while stack:
try:
last = stack[-1]
if isinstance(last, types.GeneratorType):
stack.append(last.send(last_result))
last_result = None
elif isinstance(last, ToVisit):
stack.append(self._visit(stack.pop()))
else:
last_result = stack.pop()
except StopIteration:
stack.pop()
return last_result
def _visit(self, node):
if node.obj is None:
return None
__DEBUG__("Optimizer: Visiting node {}".format(str(node.obj)), 1)
methname = 'visit_' + node.obj.token
meth = getattr(self, methname, None)
if meth is None:
meth = self.generic_visit
return meth(node.obj)
@property
def O_LEVEL(self):
return OPTIONS.optimization.value
def visit_ADDRESS(self, node):
if node.operand.token != 'ARRAYACCESS':
if not chk.is_dynamic(node.operand):
node = symbols.CONST(node, node.lineno)
elif node.operand.offset is not None: # A constant access
if node.operand.scope == SCOPE.global_: # Calculate offset if global variable
node = symbols.BINARY.make_node(
'PLUS',
symbols.UNARY('ADDRESS', node.operand.entry, node.lineno, type_=self.TYPE(gl.PTR_TYPE)),
symbols.NUMBER(node.operand.offset, lineno=node.operand.lineno, type_=self.TYPE(gl.PTR_TYPE)),
lineno=node.lineno, func=lambda x, y: x + y
)
yield node
def visit_BINARY(self, node):
node = (yield self.generic_visit(node)) # This might convert consts to numbers if possible
# Retry folding
yield symbols.BINARY.make_node(node.operator, node.left, node.right, node.lineno, node.func, node.type_)
def visit_BUILTIN(self, node):
methodname = "visit_" + node.fname
if hasattr(self, methodname):
yield (yield getattr(self, methodname)(node))
else:
yield (yield self.generic_visit(node))
def visit_CHR(self, node):
node = (yield self.generic_visit(node))
if all(chk.is_static(arg.value) for arg in node.operand):
yield symbols.STRING(''.join(
chr(api.utils.get_final_value(x.value) & 0xFF) for x in node.operand), node.lineno)
else:
yield node
def visit_CONST(self, node):
if chk.is_number(node.expr) or chk.is_const(node.expr):
yield node.expr
else:
yield node
def visit_FUNCCALL(self, node):
node.args = (yield self.generic_visit(node.args)) # Avoid infinite recursion not visiting node.entry
self._check_if_any_arg_is_an_array_and_needs_lbound_or_ubound(node.entry.params, node.args)
yield node
def visit_CALL(self, node):
node.args = (yield self.generic_visit(node.args)) # Avoid infinite recursion not visiting node.entry
self._check_if_any_arg_is_an_array_and_needs_lbound_or_ubound(node.entry.params, node.args)
yield node
def visit_FUNCDECL(self, node):
if self.O_LEVEL > 1 and not node.entry.accessed:
warning(node.entry.lineno, "Function '%s' is never called and has been ignored" % node.entry.name)
yield self.NOP
else:
node.children[1] = (yield ToVisit(node.entry))
yield node
def visit_FUNCTION(self, node):
if getattr(node, 'visited', False):
yield node
else:
node.visited = True
yield (yield self.generic_visit(node))
def visit_LET(self, node):
if self.O_LEVEL > 1 and not node.children[0].accessed:
warning_not_used(node.children[0].lineno, node.children[0].name)
yield symbols.BLOCK(*list(self.filter_inorder(node.children[1], lambda x: isinstance(x, symbols.CALL))))
else:
yield (yield self.generic_visit(node))
def visit_LETSUBSTR(self, node):
if self.O_LEVEL > 1 and not node.children[0].accessed:
warning_not_used(node.children[0].lineno, node.children[0].name)
yield self.NOP
else:
yield (yield self.generic_visit(node))
def visit_RETURN(self, node):
""" Visits only children[1], since children[0] points to
the current function being returned from (if any), and
might cause infinite recursion.
"""
if len(node.children) == 2:
node.children[1] = (yield ToVisit(node.children[1]))
yield node
def visit_UNARY(self, node):
if node.operator == 'ADDRESS':
yield (yield self.visit_ADDRESS(node))
else:
yield (yield self.generic_visit(node))
def visit_BLOCK(self, node):
if self.O_LEVEL >= 1 and chk.is_null(node):
yield self.NOP
return
yield (yield self.generic_visit(node))
def visit_IF(self, node):
expr_ = (yield ToVisit(node.children[0]))
then_ = (yield ToVisit(node.children[1]))
else_ = (yield ToVisit(node.children[2])) if len(node.children) == 3 else self.NOP
if self.O_LEVEL >= 1:
if chk.is_null(then_, else_):
api.errmsg.warning_empty_if(node.lineno)
yield self.NOP
return
block_accessed = chk.is_block_accessed(then_) or chk.is_block_accessed(else_)
if not block_accessed and chk.is_number(expr_): # constant condition
if expr_.value: # always true (then_)
yield then_
else: # always false (else_)
yield else_
return
if chk.is_null(else_) and len(node.children) == 3:
node.children.pop() # remove empty else
yield node
return
for i in range(len(node.children)):
node.children[i] = (expr_, then_, else_)[i]
yield node
def visit_WHILE(self, node):
expr_ = (yield node.children[0])
body_ = (yield node.children[1])
if self.O_LEVEL >= 1:
if chk.is_number(expr_) and not expr_.value and not chk.is_block_accessed(body_):
yield self.NOP
return
for i, child in enumerate((expr_, body_)):
node.children[i] = child
yield node
def visit_FOR(self, node):
from_ = (yield node.children[1])
to_ = (yield node.children[2])
step_ = (yield node.children[3])
body_ = (yield node.children[4])
if self.O_LEVEL > 0 and chk.is_number(from_, to_, step_) and not chk.is_block_accessed(body_):
if from_ > to_ and step_ > 0:
yield self.NOP
return
if from_ < to_ and step_ < 0:
yield self.NOP
return
for i, child in enumerate((from_, to_, step_, body_), start=1):
node.children[i] = child
yield node
# TODO: ignore unused labels
def _visit_LABEL(self, node):
if self.O_LEVEL and not node.accessed:
yield self.NOP
else:
yield node
@staticmethod
def generic_visit(node):
for i in range(len(node.children)):
node.children[i] = (yield ToVisit(node.children[i]))
yield node
def _check_if_any_arg_is_an_array_and_needs_lbound_or_ubound(self, params: symbols.PARAMLIST,
args: symbols.ARGLIST):
""" Given a list of params and a list of args, traverse them to check if any arg is a byRef array parameter,
and if so, whether it's use_lbound or use_ubound flag is updated to True and if it's a local var. If so, it's
offset size has changed and must be reevaluated!
"""
for arg, param in zip(args, params):
if not param.byref or param.class_ != CLASS.array:
continue
if arg.value.lbound_used and arg.value.ubound_used:
continue
self._update_bound_status(arg.value)
def _update_bound_status(self, arg: symbols.VARARRAY):
old_lbound_used = arg.lbound_used
old_ubound_used = arg.ubound_used
for p in arg.requires:
arg.lbound_used = arg.lbound_used or p.lbound_used
arg.ubound_used = arg.ubound_used or p.ubound_used
if old_lbound_used != arg.lbound_used or old_ubound_used != arg.ubound_used:
if arg.scope == SCOPE.global_:
return
if arg.scope == SCOPE.local and not arg.byref:
arg.scopeRef.owner.locals_size = api.symboltable.SymbolTable.compute_offsets(arg.scopeRef)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/optimize.py
|
optimize.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
import sys
# The options container
from . import options
from . import global_
from .options import ANYTYPE
# ------------------------------------------------------
# Common setup and configuration for all tools
# ------------------------------------------------------
OPTIONS = options.Options()
def init():
OPTIONS.reset()
OPTIONS.add_option('outputFileName', str)
OPTIONS.add_option('inputFileName', str)
OPTIONS.add_option('StdErrFileName', str)
OPTIONS.add_option('Debug', int, 0)
# Default console redirections
OPTIONS.add_option('stdin', ANYTYPE, sys.stdin)
OPTIONS.add_option('stdout', ANYTYPE, sys.stdout)
OPTIONS.add_option('stderr', ANYTYPE, sys.stderr)
# ----------------------------------------------------------------------
# Default Options and Compilation Flags
#
# optimization -- Optimization level. Use -O flag to change.
# case_insensitive -- Whether user identifiers are case insensitive
# or not
# array_base -- Default array lower bound
# param_byref --Default parameter passing. TRUE => By Reference
# ----------------------------------------------------------------------
OPTIONS.add_option('optimization', int, global_.DEFAULT_OPTIMIZATION_LEVEL)
OPTIONS.add_option('case_insensitive', bool, False)
OPTIONS.add_option('array_base', int, 0)
OPTIONS.add_option('byref', bool, False)
OPTIONS.add_option('max_syntax_errors', int, global_.DEFAULT_MAX_SYNTAX_ERRORS)
OPTIONS.add_option('string_base', int, 0)
OPTIONS.add_option('memory_map', str, None)
OPTIONS.add_option('bracket', bool, False)
OPTIONS.add_option('use_loader', bool, False) # Whether to use a loader
OPTIONS.add_option('autorun', bool, False) # Whether to add autostart code (needs basic loader = true)
OPTIONS.add_option('output_file_type', str, 'bin') # bin, tap, tzx etc...
OPTIONS.add_option('include_path', str, '') # Include path, like '/var/lib:/var/include'
OPTIONS.add_option('memoryCheck', bool, False)
OPTIONS.add_option('strictBool', bool, False)
OPTIONS.add_option('arrayCheck', bool, False)
OPTIONS.add_option('enableBreak', bool, False)
OPTIONS.add_option('emitBackend', bool, False)
OPTIONS.add_option('arch', str, 'zx48k')
OPTIONS.add_option('__DEFINES', dict, {})
OPTIONS.add_option('explicit', bool, False)
OPTIONS.add_option('Sinclair', bool, False)
OPTIONS.add_option('strict', bool, False) # True to force type checking
OPTIONS.add_option('zxnext', bool, False) # True to enable ZX Next ASM opcodes
init()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/config.py
|
config.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# Simple global container for internal constants.
# Internal constants might be architecture dependant. They're set
# on module init (at __init__.py) on api.arch.<arch>/init.py
#
# Don't touch unless you know what are you doing
# ----------------------------------------------------------------------
from .opcodestemps import OpcodesTemps
from .constants import TYPE
# ----------------------------------------------------------------------
# Initializes a singleton container
# ----------------------------------------------------------------------
optemps = OpcodesTemps() # Must be initialized with OpcodesTemps()
# ----------------------------------------------------------------------
# PUSH / POP loops for taking into account which nested-loop level
# the parser is in. Each element of the list must be a t-uple. And
# each t-uple must have at least one element (a string), which contains
# which kind of loop the parser is in: e.g. 'FOR', 'WHILE', or 'DO'.
# Nested loops are appended at the end, and popped out on loop exit.
# ----------------------------------------------------------------------
LOOPS = []
# ----------------------------------------------------------------------
# Each new scope push the current LOOPS state and reset LOOPS. Upon
# scope exit, the previous LOOPS is restored and popped out of the
# META_LOOPS stack.
# ----------------------------------------------------------------------
META_LOOPS = []
# ----------------------------------------------------------------------
# Number of parser (both syntactic & semantic) errors found. If not 0
# at the end, no asm output will be emitted.
# ----------------------------------------------------------------------
has_errors = 0 # Number of errors
has_warnings = 0 # Number of warnings
# ----------------------------------------------------------------------
# Default var type when not specified (implicit) an can't be guessed
# ----------------------------------------------------------------------
DEFAULT_TYPE = TYPE.float_
# ----------------------------------------------------------------------
# Default variable type when not specified in DIM.
# 'auto' => try to guess and if not, fallback to DEFAULT_TYPE
# ----------------------------------------------------------------------
DEFAULT_IMPLICIT_TYPE = TYPE.auto # Use TYPE.auto for smart type guessing
# ----------------------------------------------------------------------
# Maximum number of errors to report before giving up.
# ----------------------------------------------------------------------
DEFAULT_MAX_SYNTAX_ERRORS = 20
# ----------------------------------------------------------------------
# The current filename being processed (changes with each #include)
# ----------------------------------------------------------------------
FILENAME = '(stdin)' # name of current file being parsed
# ----------------------------------------------------------------------
# Global Symbol Table
# ----------------------------------------------------------------------
SYMBOL_TABLE = None # Must be initialized with SymbolTable()
# ----------------------------------------------------------------------
# Function calls pending to check
# Each scope pushes (prepends) an empty list
# ----------------------------------------------------------------------
FUNCTION_CALLS = []
# ----------------------------------------------------------------------
# Function level entry ID in which scope we are in. If the list
# is empty, we are at GLOBAL scope
# ----------------------------------------------------------------------
FUNCTION_LEVEL = []
# ----------------------------------------------------------------------
# Initialization routines to be called automatically at program start
# ----------------------------------------------------------------------
INITS = set([])
# ----------------------------------------------------------------------
# FUNCTIONS pending to translate after parsing stage
# ----------------------------------------------------------------------
FUNCTIONS = []
# ----------------------------------------------------------------------
# Parameter alignment. Must be set by arch.<arch>.__init__
# ----------------------------------------------------------------------
PARAM_ALIGN = None # Set to None, so if not set will raise error
# ----------------------------------------------------------------------
# Data type used for array boundaries. Must be an integral
# ----------------------------------------------------------------------
BOUND_TYPE = None # Set to None, so if not set will raise error
# ----------------------------------------------------------------------
# Data type used for elements size. Must be an integral
# ----------------------------------------------------------------------
SIZE_TYPE = None
# ----------------------------------------------------------------------
# Data Type used for string chars index. Must be an integral
# ----------------------------------------------------------------------
STR_INDEX_TYPE = None
# ----------------------------------------------------------------------
# MIN and MAX str slice index
# ----------------------------------------------------------------------
MIN_STRSLICE_IDX = None # Min. string slicing position
MAX_STRSLICE_IDX = None # Max. string slicing position
# ----------------------------------------------------------------------
# Type used internally for pointer and memory addresses
# ----------------------------------------------------------------------
PTR_TYPE = None
# ----------------------------------------------------------------------
# Character used for name mangling. Usually '_' or '.'
# ----------------------------------------------------------------------
MANGLE_CHR = '_'
# ----------------------------------------------------------------------
# Prefix used in labels to mark the beginning of array data
# ----------------------------------------------------------------------
ARRAY_DATA_PREFIX = '__DATA__'
# ----------------------------------------------------------------------
# Default optimization level
# ----------------------------------------------------------------------
DEFAULT_OPTIMIZATION_LEVEL = 2 # Optimization level. Higher -> more optimized
# ----------------------------------------------------------------------
# DATA blocks
# ----------------------------------------------------------------------
DATAS = []
DATA_LABELS_REQUIRED = set() # DATA labels used by RESTORE that must be emitted
DATA_LABELS = {} # Maps declared labels to current data ptr
DATA_PTR_CURRENT = None
DATA_IS_USED = False
DATA_FUNCTIONS = [] # Counts the number of funcptrs emitted
# ----------------------------------------------------------------------
# Cache of Message errors to avoid repetition
# ----------------------------------------------------------------------
error_msg_cache = set()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/global_.py
|
global_.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import inspect
import os
class classproperty(object):
''' Decorator for class properties.
Use @classproperty instead of @property to add properties
to the class object.
'''
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
def check_type(*args, **kwargs):
''' Checks the function types
'''
args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args)
kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs}
def decorate(func):
types = args
kwtypes = kwargs
gi = "Got <{}> instead"
errmsg1 = "to be of type <{}>. " + gi
errmsg2 = "to be one of type ({}). " + gi
errar = "{}:{} expected '{}' "
errkw = "{}:{} expected {} "
def check(*ar, **kw):
line = inspect.getouterframes(inspect.currentframe())[1][2]
fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])
for arg, type_ in zip(ar, types):
if type(arg) not in type_:
if len(type_) == 1:
raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__,
type(arg).__name__))
else:
raise TypeError((errar + errmsg2).format(fname, line, arg,
', '.join('<%s>' % x.__name__ for x in type_),
type(arg).__name__))
for kwarg in kw:
if kwtypes.get(kwarg, None) is None:
continue
if type(kw[kwarg]) not in kwtypes[kwarg]:
if len(kwtypes[kwarg]) == 1:
raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__,
type(kw[kwarg]).__name__))
else:
raise TypeError((errkw + errmsg2).format(
fname,
line,
kwarg,
', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]),
type(kw[kwarg]).__name__)
)
return func(*ar, **kw)
return check
return decorate
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/decorator.py
|
decorator.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
class __Singleton(object):
pass
singleton = __Singleton()
singleton.table = {}
singleton.count = 0
class OpcodesTemps(object):
""" Manages a table of Tn temporal values.
This should be a SINGLETON container
"""
def __init__(self):
self.data = singleton
def new_t(self):
""" Returns a new t-value name
"""
self.data.count += 1
return 't%i' % (self.data.count - 1)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/opcodestemps.py
|
opcodestemps.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
# ------------------------- ERROR exception classes ---------------------------
__all__ = ['Error']
class Error(Exception):
"""Base class for exceptions in this module.
"""
def __init__(self, msg='Unknown error'):
self.msg = msg
def __str__(self):
return self.msg
class InvalidOperatorError(Error):
def __init__(self, operator):
self.msg = 'Invalid operator "%s"' % str(operator)
class InvalidLoopError(Error):
def __init__(self, loop):
self.msg = 'Invalid loop type error (not found?) "%s"' % str(loop)
class InvalidCONSTexpr(Error):
def __init__(self, symbol):
self.msg = "Invalid CONST expression: %s|%s" % (symbol.token, symbol.t)
class InvalidBuiltinFunctionError(Error):
def __init__(self, fname):
self.msg = "Invalid BUILTIN function '%s'" % fname
class InternalError:
def __init__(self, msg):
self.msg = msg
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/errors.py
|
errors.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from collections import OrderedDict
from .debug import __DEBUG__
import symbols
from symbols.symbol_ import Symbol
from . import global_
from .config import OPTIONS
from .errmsg import error as syntax_error
from .errmsg import warning_implicit_type
from .errmsg import warning_not_used
from .errmsg import syntax_error_func_type_mismatch
from .errmsg import syntax_error_not_array_nor_func
from .constants import DEPRECATED_SUFFIXES
from .constants import SUFFIX_TYPE
from .constants import SCOPE
from .constants import CLASS
from .constants import TYPE
from .check import is_number
from .check import check_is_declared_explicit
# ----------------------------------------------------------------------
# Symbol table. Each id level will push a new symbol table
# ----------------------------------------------------------------------
class SymbolTable(object):
""" Implements a symbol table.
This symbol table stores symbols for types, functions and variables.
Variables can be in the global or local scope. Each symbol can be
retrieved by its name.
Parameters are treated like local variables, but use a different
class (PARAMDECL) and has their scope set to SCOPE.parameter.
Arrays are also a derived class from var. The scope rules above
also apply for arrays (local, global), except for parameters.
The symbol table is implemented as a list of Scope instances.
To get a symbol by its id, just call symboltable.get_id(id, scope).
If scope is not given, it will search from the current scope to
the global one, 'un-nesting' them.
An scope is referenced by a number (it's position in the list).
Do not use 0 to reference the global scope. Use symboltable.global_scope
and symboltable.current_scope to get such numbers.
Accessing symboltable[symboltable.current_scope] returns an Scope object.
"""
class Scope(object):
""" Implements an Scope.
An Scope is just a dictionary.
To get a symbol, just access it by it's name. So scope['a'] will
return the 'a' symbol (e.g. a declared variable 'a') or None
if nothing is declared in that scope (no KeyError exception is raised
if the identifier is not defined in such scope).
The caseins dict stores the symbol names in lowercase only if
the global OPTION ignore case is enabled (True). This is because
most BASIC dialects are case insensitive. 'caseins' will be used
as a fallback if the symbol name does not exists.
On init() the parent mangle can be stored. The mangle is a prefix
added to every symbol to avoid name collision.
E.g. for a global var o function, the mangle will be '_'. So
'a' will be output in asm as '_a'. For nested scopes, the mangled
is composed as _functionname_varname. So a local variable in function
myFunct will be output as _myFunct_a.
"""
def __init__(self, mangle='', parent_mangle=''):
self.symbols = OrderedDict()
self.caseins = OrderedDict()
self.parent_mangle = parent_mangle
self.mangle = mangle
self.ownwer: Symbol = None # Function, Sub, etc. owning this scope
def __getitem__(self, key):
return self.symbols.get(key, self.caseins.get(key.lower(), None))
def __setitem__(self, key, value):
assert isinstance(value, Symbol)
self.symbols[key] = value
if value.caseins: # Declared with case insensitive option?
self.caseins[key.lower()] = value
def __delitem__(self, key):
symbol = self[key]
if symbol is None:
return
del self.symbols[key]
if symbol.caseins:
del self.caseins[key.lower()]
def values(self, filter_by_opt=True):
if filter_by_opt and OPTIONS.optimization.value > 1:
return [y for x, y in self.symbols.items() if y.accessed]
return [y for x, y in self.symbols.items()]
def keys(self, filter_by_opt=True):
if filter_by_opt and OPTIONS.optimization.value > 1:
return [x for x, y in self.symbols.items() if y.accessed]
return self.symbols.keys()
def items(self, filter_by_opt=True):
if filter_by_opt and OPTIONS.optimization.value > 1:
return [(x, y) for x, y in self.symbols.items() if y.accessed]
return self.symbols.items()
def __init__(self):
""" Initializes the Symbol Table
"""
self.mangle = '' # Prefix for local variables
self.table = [SymbolTable.Scope(self.mangle)]
self.basic_types = {}
# Initialize canonical types
for type_ in TYPE.types:
self.basic_types[type_] = self.declare_type(symbols.BASICTYPE(type_))
@property
def current_scope(self) -> int:
return len(self.table) - 1
@property
def global_scope(self):
return 0
def get_entry(self, id_: str, scope=None):
""" Returns the ID entry stored in self.table, starting
by the first one. Returns None if not found.
If scope is not None, only the given scope is searched.
"""
if id_[-1] in DEPRECATED_SUFFIXES:
id_ = id_[:-1] # Remove it
if scope is not None:
assert len(self.table) > scope
return self[scope][id_]
for sc in self:
if sc[id_] is not None:
return sc[id_]
return None # Not found
def declare(self, id_: str, lineno: int, entry):
""" Check there is no 'id' already declared in the current scope, and
creates and returns it. Otherwise, returns None,
and the caller function raises the syntax/semantic error.
Parameter entry is the SymbolVAR, SymbolVARARRAY, etc. instance
The entry 'declared' field is leave untouched. Setting it if on
behalf of the caller.
"""
id2 = id_
type_ = entry.type_
if id2[-1] in DEPRECATED_SUFFIXES:
id2 = id2[:-1] # Remove it
type_ = symbols.TYPEREF(self.basic_types[SUFFIX_TYPE[id_[-1]]], lineno) # Overrides type_
if entry.type_ is not None and not entry.type_.implicit and type_ != entry.type_:
syntax_error(lineno, "expected type {2} for '{0}', got {1}".format(id_, entry.type_.name, type_.name))
# Checks if already declared
if self[self.current_scope][id2] is not None:
return None
entry.caseins = OPTIONS.case_insensitive.value
self[self.current_scope][id2] = entry
entry.name = id2 # Removes DEPRECATED SUFFIXES if any
if isinstance(entry, symbols.TYPE):
return entry # If it's a type declaration, we're done
# HINT: The following should be done by the respective callers!
# entry.callable = None # True if function, strings or arrays
# entry.class_ = None # TODO: important
entry.forwarded = False # True for a function header
entry.mangled = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, entry.name) # Mangled name
entry.type_ = type_ # type_ now reflects entry sigil (i.e. a$ => 'string' type) if any
entry.scopeRef = self[self.current_scope]
return entry
# -------------------------------------------------------------------------
# Symbol Table Checks
# -------------------------------------------------------------------------
def check_is_declared(self, id_: str, lineno: int, classname='identifier',
scope=None, show_error=True):
""" Checks if the given id is already defined in any scope
or raises a Syntax Error.
Note: classname is not the class attribute, but the name of
the class as it would appear on compiler messages.
"""
result = self.get_entry(id_, scope)
if isinstance(result, symbols.TYPE):
return True
if result is None or not result.declared:
if show_error:
syntax_error(lineno, 'Undeclared %s "%s"' % (classname, id_))
return False
return True
def check_is_undeclared(self, id_: str, lineno: int, classname='identifier',
scope=None, show_error=False):
""" The reverse of the above.
Check the given identifier is not already declared. Returns True
if OK, False otherwise.
"""
result = self.get_entry(id_, scope)
if result is None or not result.declared:
return True
if scope is None:
scope = self.current_scope
if show_error:
syntax_error(lineno,
'Duplicated %s "%s" (previous one at %s:%i)' %
(classname, id_, self.table[scope][id_].filename,
self.table[scope][id_].lineno))
return False
def check_class(self, id_: str, class_, lineno: int, scope=None, show_error=True):
""" Check the id is either undefined or defined with
the given class.
- If the identifier (e.g. variable) does not exists means
it's undeclared, and returns True (OK).
- If the identifier exists, but its class_ attribute is
unknown yet (None), returns also True. This means the
identifier has been referenced in advanced and it's undeclared.
Otherwise fails returning False.
"""
assert CLASS.is_valid(class_)
entry = self.get_entry(id_, scope)
if entry is None or entry.class_ == CLASS.unknown: # Undeclared yet
return True
if entry.class_ != class_:
if show_error:
if entry.class_ == CLASS.array:
a1 = 'n'
else:
a1 = ''
if class_ == CLASS.array:
a2 = 'n'
else:
a2 = ''
syntax_error(lineno, "identifier '%s' is a%s %s, not a%s %s" %
(id_, a1, entry.class_, a2, class_))
return False
return True
# -------------------------------------------------------------------------
# Scope Management
# -------------------------------------------------------------------------
def enter_scope(self, funcname):
""" Starts a new variable scope.
Notice the *IMPORTANT* marked lines. This is how a new scope is added,
by pushing a new dict at the end (and popped out later).
"""
old_mangle = self.mangle
self.mangle = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, funcname)
self.table.append(SymbolTable.Scope(self.mangle, parent_mangle=old_mangle))
global_.META_LOOPS.append(global_.LOOPS) # saves current LOOPS state
global_.LOOPS = [] # new LOOPS state
@staticmethod
def compute_offsets(scope: Scope) -> int:
def entry_size(var_entry):
""" For local variables and params, returns the real variable or
local array size in bytes
"""
if var_entry.scope == SCOPE.global_ or var_entry.is_aliased: # aliases or global variables = 0
return 0
if var_entry.class_ != CLASS.array:
return var_entry.size
return var_entry.memsize
entries = sorted(scope.values(filter_by_opt=True), key=entry_size)
offset = 0
for entry in entries: # Symbols of the current level
if entry.class_ in (CLASS.function, CLASS.label, CLASS.type_):
continue
# Local variables offset
if entry.class_ == CLASS.var and entry.scope == SCOPE.local:
if entry.alias is not None: # alias of another variable?
if entry.offset is None:
entry.offset = entry.alias.offset
else:
entry.offset = entry.alias.offset - entry.offset
else:
offset += entry_size(entry)
entry.offset = offset
if entry.class_ == CLASS.array and entry.scope == SCOPE.local:
entry.offset = entry_size(entry) + offset
offset = entry.offset
return offset
def leave_scope(self):
""" Ends a function body and pops current scope out of the symbol table.
"""
for v in self.table[self.current_scope].values(filter_by_opt=False):
if not v.accessed:
if v.scope == SCOPE.parameter:
kind = 'Parameter'
v.accessed = True # HINT: Parameters must always be present even if not used!
if not v.byref: # HINT: byref is always marked as used: it can be used to return a value
warning_not_used(v.lineno, v.name, kind=kind)
for entry in self.table[self.current_scope].values(filter_by_opt=True): # Symbols of the current level
if entry.class_ is CLASS.unknown:
self.move_to_global_scope(entry.name)
offset = self.compute_offsets(self.table[self.current_scope])
self.mangle = self[self.current_scope].parent_mangle
self.table.pop()
global_.LOOPS = global_.META_LOOPS.pop()
return offset
def move_to_global_scope(self, id_: str):
""" If the given id is in the current scope, and there is more than
1 scope, move the current id to the global scope and make it global.
Labels need this.
"""
# In the current scope and more than 1 scope?
if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1:
symbol = self.table[self.current_scope][id_]
symbol.offset = None
symbol.scope = SCOPE.global_
if symbol.class_ != CLASS.label:
symbol.mangled = "%s%s%s" % (self.table[self.global_scope].mangle, global_.MANGLE_CHR, id_)
self.table[self.global_scope][id_] = symbol
del self.table[self.current_scope][id_] # Removes it from the current scope
__DEBUG__("'{}' entry moved to global scope".format(id_))
def make_static(self, id_: str):
""" The given ID in the current scope is changed to 'global', but the
variable remains in the current scope, if it's a 'global private'
variable: A variable private to a function scope, but whose contents
are not in the stack, not in the global variable area.
These are called 'static variables' in C.
A copy of the instance, but mangled, is also allocated in the global
symbol table.
"""
entry = self.table[self.current_scope][id_]
entry.scope = SCOPE.global_
self.table[self.global_scope][entry.mangled] = entry
# -------------------------------------------------------------------------
# Identifier Declaration (e.g DIM, FUNCTION, SUB, etc.)
# -------------------------------------------------------------------------
@staticmethod
def update_aliases(entry):
""" Given an entry, checks its aliases (if any), and updates
it's back pointers (aliased_by array).
"""
for symbol in entry.aliased_by:
symbol.alias = entry
def access_id(self, id_: str, lineno: int, scope=None, default_type=None, default_class=CLASS.unknown):
""" Access a symbol by its identifier and checks if it exists.
If not, it's supposed to be an implicit declared variable.
default_class is the class to use in case of an undeclared-implicit-accessed id
"""
if isinstance(default_type, symbols.BASICTYPE):
default_type = symbols.TYPEREF(default_type, lineno, implicit=False)
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
if not check_is_declared_explicit(lineno, id_):
return None
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_IMPLICIT_TYPE],
lineno, implicit=True)
result = self.declare_variable(id_, lineno, default_type)
result.declared = False # It was implicitly declared
result.class_ = default_class
return result
# The entry was already declared. If it's type is auto and the default type is not None,
# update its type.
if default_type is not None and result.type_ == self.basic_types[TYPE.auto]:
result.type_ = default_type
warning_implicit_type(lineno, id_, default_type)
return result
def access_var(self, id_: str, lineno: int, scope=None, default_type=None):
"""
Since ZX BASIC allows access to undeclared variables, we must allow
them, and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry so.
Otherwise, creates an implicit declared variable entry and returns it.
If the --strict command line flag is enabled (or #pragma option explicit
is in use) checks ensures the id_ is already declared.
Returns None on error.
"""
result = self.access_id(id_, lineno, scope, default_type)
if result is None:
return None
if not self.check_class(id_, CLASS.var, lineno, scope):
return None
assert isinstance(result, symbols.VAR)
result.class_ = CLASS.var
return result
def access_array(self, id_: str, lineno: int, scope=None, default_type=None):
"""
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
"""
if not self.check_is_declared(id_, lineno, 'array', scope):
return None
if not self.check_class(id_, CLASS.array, lineno, scope):
return None
return self.access_id(id_, lineno, scope=scope, default_type=default_type)
def access_func(self, id_: str, lineno: int, scope=None, default_type=None):
"""
Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Otherwise, creates an implicit declared variable entry and returns it.
"""
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
if global_.DEFAULT_IMPLICIT_TYPE == TYPE.auto:
default_type = symbols.TYPEREF(self.basic_types[TYPE.auto], lineno, implicit=True)
else:
default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_TYPE], lineno, implicit=True)
return self.declare_func(id_, lineno, default_type)
if not self.check_class(id_, CLASS.function, lineno, scope):
return None
return result
def access_call(self, id_: str, lineno: int, scope=None, type_=None):
""" Creates a func/array/string call. Checks if id is callable or not.
An identifier is "callable" if it can be followed by a list of para-
meters.
This does not mean the id_ is a function, but that it allows the same
syntax a function does:
For example:
- MyFunction(a, "hello", 5) is a Function so MyFuncion is callable
- MyArray(5, 3.7, VAL("32")) makes MyArray identifier "callable".
- MyString(5 TO 7) or MyString(5) is a "callable" string.
"""
entry = self.access_id(id_, lineno, scope, default_type=type_)
if entry is None:
return self.access_func(id_, lineno)
if entry.callable is False: # Is it NOT callable?
if entry.type_ != self.basic_types[TYPE.string]:
syntax_error_not_array_nor_func(lineno, id_)
return None
else: # Ok, it is a string slice if it has 0 or 1 parameters
return entry
if entry.callable is None and entry.type_ == self.basic_types[TYPE.string]:
# Ok, it is a string slice if it has 0 or 1 parameters
entry.callable = False
return entry
# Mangled name (functions always has _name as mangled)
# entry.mangled = '_%s' % entry.name
# entry.callable = True # HINT: must be true already
return entry
def access_label(self, id_, lineno, scope=None):
result = self.get_entry(id_, scope)
if result is None:
result = self.declare_label(id_, lineno)
result.declared = False
else:
if not self.check_class(id_, CLASS.label, lineno, scope, show_error=True):
return None
if not isinstance(result, symbols.LABEL): # An undeclared label used in advance
symbols.VAR.to_label(result)
result.accessed = True
return result
def declare_variable(self, id_, lineno, type_, default_value=None):
""" Like the above, but checks that entry.declared is False.
Otherwise raises an error.
Parameter default_value specifies an initialized variable, if set.
"""
assert isinstance(type_, symbols.TYPEREF)
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Variable '%s' already declared as a parameter "
"at %s:%i" % (id_, entry.filename, entry.lineno))
else:
syntax_error(lineno, "Variable '%s' already declared at "
"%s:%i" % (id_, entry.filename, entry.lineno))
return None
if not self.check_class(id_, CLASS.var, lineno, scope=self.current_scope):
return None
entry = (self.get_entry(id_, scope=self.current_scope) or
self.declare(id_, lineno, symbols.VAR(id_, lineno, class_=CLASS.var)))
__DEBUG__("Entry %s declared with class %s at scope %i" % (entry.name, CLASS.to_string(entry.class_),
self.current_scope))
if entry.type_ is None or entry.type_ == self.basic_types[TYPE.unknown]:
entry.type_ = type_
if entry.type_ != type_:
if not type_.implicit and entry.type_ is not None:
syntax_error(lineno,
"'%s' suffix is for type '%s' but it was "
"declared as '%s'" %
(id_, entry.type_, type_))
return None
entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
entry.callable = False
entry.class_ = CLASS.var # HINT: class_ attribute could be erased if access_id was used.
entry.declared = True # marks it as declared
if entry.type_.implicit and entry.type_ != self.basic_types[TYPE.unknown]:
warning_implicit_type(lineno, id_, entry.type_.name)
if default_value is not None and entry.type_ != default_value.type_:
if is_number(default_value):
default_value = symbols.TYPECAST.make_node(entry.type_, default_value,
lineno)
if default_value is None:
return None
else:
syntax_error(lineno,
"Variable '%s' declared as '%s' but initialized "
"with a '%s' value" %
(id_, entry.type_, default_value.type_))
return None
entry.default_value = default_value
return entry
def declare_type(self, type_):
""" Declares a type.
Checks its name is not already used in the current scope,
and that it's not a basic type.
Returns the given type_ Symbol, or None on error.
"""
assert isinstance(type_, symbols.TYPE)
# Checks it's not a basic type
if not type_.is_basic and type_.name.lower() in TYPE.TYPE_NAMES.values():
syntax_error(type_.lineno, "'%s' is a basic type and cannot be redefined" %
type_.name)
return None
if not self.check_is_undeclared(type_.name, type_.lineno, scope=self.current_scope, show_error=True):
return None
entry = self.declare(type_.name, type_.lineno, type_)
return entry
def declare_const(self, id_: str, lineno: int, type_, default_value):
""" Similar to the above. But declares a Constant.
"""
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Constant '%s' already declared as a parameter "
"at %s:%i" % (id_, entry.filename, entry.lineno))
else:
syntax_error(lineno, "Constant '%s' already declared at "
"%s:%i" % (id_, entry.filename, entry.lineno))
return None
entry = self.declare_variable(id_, lineno, type_, default_value)
if entry is None:
return None
entry.class_ = CLASS.const
return entry
def declare_label(self, id_: str, lineno: int):
""" Declares a label (line numbers are also labels).
Unlike variables, labels are always global.
"""
# TODO: consider to make labels private
id1 = id_
id_ = str(id_)
if not self.check_is_undeclared(id_, lineno, 'label'):
entry = self.get_entry(id_)
syntax_error(lineno, "Label '%s' already used at %s:%i" %
(id_, entry.filename, entry.lineno))
return entry
entry = self.get_entry(id_)
if entry is not None and entry.declared:
if entry.is_line_number:
syntax_error(lineno, "Duplicated line number '%s'. "
"Previous was at %i" % (entry.name, entry.lineno))
else:
syntax_error(lineno, "Label '%s' already declared at line %i" %
(id_, entry.lineno))
return None
entry = (self.get_entry(id_, scope=self.current_scope) or
self.get_entry(id_, scope=self.global_scope) or
self.declare(id_, lineno, symbols.LABEL(id_, lineno)))
if entry is None:
return None
if not isinstance(entry, symbols.LABEL):
entry = symbols.VAR.to_label(entry)
if id_[0] == '.':
id_ = id_[1:]
# HINT: ??? Mangled name. Just the label, 'cause it starts with '.'
entry.mangled = '%s' % id_
else:
# HINT: Mangled name. Labels are __LABEL__
entry.mangled = '__LABEL__%s' % entry.name
entry.is_line_number = isinstance(id1, int)
if global_.FUNCTION_LEVEL:
entry.scope_owner = list(global_.FUNCTION_LEVEL)
self.move_to_global_scope(id_) # Labels are always global # TODO: not in the future
entry.declared = True
entry.type_ = self.basic_types[global_.PTR_TYPE]
return entry
def declare_param(self, id_: str, lineno: int, type_=None, is_array=False):
""" Declares a parameter
Check if entry.declared is False. Otherwise raises an error.
"""
if not self.check_is_undeclared(id_, lineno, classname='parameter',
scope=self.current_scope, show_error=True):
return None
if is_array:
entry = self.declare(id_, lineno, symbols.VARARRAY(id_, symbols.BOUNDLIST(), lineno, None, type_))
entry.callable = True
entry.scope = SCOPE.parameter
else:
entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_))
if entry is None:
return
entry.declared = True
if entry.type_.implicit:
warning_implicit_type(lineno, id_, type_)
return entry
def declare_array(self, id_: str, lineno: int, type_, bounds, default_value=None, addr=None):
""" Declares an array in the symbol table (VARARRAY). Error if already
exists.
The optional parameter addr specifies if the array elements must be placed at an specific
(constant) memory address.
"""
assert isinstance(type_, symbols.TYPEREF)
assert isinstance(bounds, symbols.BOUNDLIST)
if not self.check_class(id_, CLASS.array, lineno, scope=self.current_scope):
return None
entry = self.get_entry(id_, self.current_scope)
if entry is None:
entry = self.declare(id_, lineno, symbols.VARARRAY(id_, bounds, lineno, type_=type_))
if not entry.declared:
if entry.callable:
syntax_error(lineno,
"Array '%s' must be declared before use. "
"First used at line %i" %
(id_, entry.lineno))
return None
else:
if entry.scope == SCOPE.parameter:
syntax_error(lineno, "variable '%s' already declared as a "
"parameter at line %i" % (id_, entry.lineno))
else:
syntax_error(lineno, "variable '%s' already declared at "
"line %i" % (id_, entry.lineno))
return None
if entry.type_ != self.basic_types[TYPE.unknown] and entry.type_ != type_:
if not type_.implicit:
syntax_error(lineno, "Array suffix for '%s' is for type '%s' "
"but declared as '%s'" %
(entry.name, entry.type_, type_))
return None
type_.implicit = False
type_ = entry.type_
if type_.implicit:
warning_implicit_type(lineno, id_, type_)
if not isinstance(entry, symbols.VARARRAY):
entry = symbols.VAR.to_vararray(entry, bounds)
entry.declared = True
entry.type_ = type_
entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
entry.default_value = default_value
entry.callable = True
entry.class_ = CLASS.array
entry.addr = addr
__DEBUG__('Entry %s declared with class %s at scope %i' % (id_, CLASS.to_string(entry.class_),
self.current_scope))
return entry
def declare_func(self, id_: str, lineno: int, type_=None):
""" Declares a function in the current scope.
Checks whether the id exist or not (error if exists).
And creates the entry at the symbol table.
"""
if not self.check_class(id_, 'function', lineno):
entry = self.get_entry(id_) # Must not exist or have _class = None or Function and declared = False
an = 'an' if entry.class_.lower()[0] in 'aeio' else 'a'
syntax_error(lineno, "'%s' already declared as %s %s at %i" % (id_, an, entry.class_, entry.lineno))
return None
entry = self.get_entry(id_) # Must not exist or have _class = None or Function and declared = False
if entry is not None:
if entry.declared and not entry.forwarded:
syntax_error(lineno, "Duplicate function name '%s', previously defined at %i" % (id_, entry.lineno))
return None
if entry.class_ != CLASS.unknown and entry.callable is False: # HINT: Must use is False here.
syntax_error_not_array_nor_func(lineno, id_)
return None
if id_[-1] in DEPRECATED_SUFFIXES and entry.type_ != self.basic_types[SUFFIX_TYPE[id_[-1]]]:
syntax_error_func_type_mismatch(lineno, entry)
if entry.token == 'VAR': # This was a function used in advance
symbols.VAR.to_function(entry, lineno=lineno)
entry.mangled = '%s_%s' % (self.mangle, entry.name) # HINT: mangle for nexted scopes
else:
entry = self.declare(id_, lineno, symbols.FUNCTION(id_, lineno, type_=type_))
if entry.forwarded:
entry.forwared = False # No longer forwarded
old_type = entry.type_ # Remembers the old type
if entry.type_ is not None:
if entry.type_ != old_type:
syntax_error_func_type_mismatch(lineno, entry)
else:
entry.type_ = old_type
else:
entry.params_size = 0 # Size of parameters
entry.locals_size = 0 # Size of local variables
return entry
def check_labels(self):
""" Checks if all the labels has been declared
"""
for entry in self.labels:
self.check_is_declared(entry.name, entry.lineno, CLASS.label)
def check_classes(self, scope=-1):
""" Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked.
"""
for entry in self[scope].values():
if entry.class_ is None:
syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name)
# -------------------------------------------------------------------------
# Properties
# -------------------------------------------------------------------------
@property
def vars_(self):
""" Returns symbol instances corresponding to variables
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]
@property
def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
@property
def types(self):
""" Returns symbol instances corresponding to type declarations
within the current scope.
"""
return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]
@property
def arrays(self):
""" Returns symbol instances corresponding to arrays
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
@property
def functions(self):
""" Returns symbol instances corresponding to functions
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ in
(CLASS.function, CLASS.sub)]
@property
def aliases(self):
""" Returns symbol instances corresponding to aliased vars.
"""
return [x for x in self[self.current_scope].values() if x.is_aliased]
def __getitem__(self, level):
""" Returns the SYMBOL TABLE for the given scope
"""
return self.table[level]
def __iter__(self):
""" Iterates through scopes, from current one (innermost) to global
(outermost)
"""
for i in range(self.current_scope, -1, -1):
yield self.table[i]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/symboltable.py
|
symboltable.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shelve
from typing import NamedTuple, List, Any
from . import constants
from . import global_
from . import errmsg
from . import check
import symbols
__all__ = ['read_txt_file', 'open_file', 'sanitize_filename', 'flatten_list']
__doc__ = """Utils module contains many helpers for several task, like reading files
or path management"""
SHELVE_PATH = os.path.join(constants.ZXBASIC_ROOT, 'parsetab', 'tabs.dbm')
SHELVE = shelve.open(SHELVE_PATH)
class DataRef(NamedTuple):
label: str
datas: List[Any]
def read_txt_file(fname):
"""Reads a txt file, regardless of its encoding
"""
encodings = ['utf-8-sig', 'cp1252']
with open(fname, 'rb') as f:
content = bytes(f.read())
for i in encodings:
try:
result = content.decode(i)
return result
except UnicodeDecodeError:
pass
global_.FILENAME = fname
errmsg.error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings))
return ''
def open_file(fname, mode='rb', encoding='utf-8'):
""" An open() wrapper for PY2 and PY3 which allows encoding
:param fname: file name (string)
:param mode: file mode (string) optional
:param encoding: optional encoding (string). Ignored in python2 or if not in text mode
:return: an open file handle
"""
if 't' not in mode:
kwargs = {}
else:
kwargs = {'encoding': encoding}
return open(fname, mode, **kwargs)
def sanitize_filename(fname):
""" Given a file name (string) returns it with back-slashes reversed.
This is to make all BASIC programs compatible in all OSes
"""
return fname.replace('\\', '/')
def current_data_label():
""" Returns a data label to which all labels must point to, until
a new DATA line is declared
"""
return '__DATA__{0}'.format(len(global_.DATAS))
def flatten_list(x):
result = []
for l in x:
if not isinstance(l, list):
result.append(l)
else:
result.extend(flatten_list(l))
return result
def parse_int(str_num):
""" Given an integer number, return its value,
or None if it could not be parsed.
Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh)
:param str_num: (string) the number to be parsed
:return: an integer number or None if it could not be parsedd
"""
str_num = (str_num or "").strip().upper()
if not str_num:
return None
base = 10
if str_num.startswith('0X'):
base = 16
str_num = str_num[2:]
if str_num.endswith('H'):
base = 16
str_num = str_num[:-1]
if str_num.startswith('$'):
base = 16
str_num = str_num[1:]
try:
return int(str_num, base)
except ValueError:
return None
def load_object(key):
return SHELVE[key] if key in SHELVE else None
def save_object(key, obj):
SHELVE[key] = obj
SHELVE.sync()
return obj
def get_or_create(key, fn):
return load_object(key) or save_object(key, fn())
def get_final_value(symbol: symbols.SYMBOL):
assert check.is_static(symbol)
result = symbol
while hasattr(result, 'value'):
result = result.value
return result
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/utils.py
|
utils.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:
class IdentitySet:
""" This set implementation only adds items
if they are not exactly the same (same reference)
preserving its order (OrderedDict). Allows deleting by ith-index.
"""
def __init__(self, elems=None):
self.elems = []
self._elems = set()
self.update(elems or [])
def add(self, elem):
self.elems.append(elem)
self._elems.add(elem)
def remove(self, elem):
""" Removes an element if it exits. Otherwise does nothing.
Returns if the element was removed.
"""
if elem in self._elems:
self._elems.remove(elem)
self.elems = [x for x in self.elems if x in self._elems]
return True
return False
def __len__(self):
return len(self.elems)
def __getitem__(self, key):
return self.elems[key]
def __str__(self):
return str(self.elems)
def __contains__(self, elem):
return elem in self._elems
def __delitem__(self, key):
self.pop(self.elems.index(key))
def intersection(self, other):
return IdentitySet(self._elems.intersection(other))
def union(self, other):
return IdentitySet(self.elems + [x for x in other])
def pop(self, i):
result = self.elems.pop(i)
self._elems.remove(result)
return result
def update(self, elems):
self.elems.extend(x for x in elems if x not in self._elems)
self._elems.update(x for x in elems)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/identityset.py
|
identityset.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/__init__.py
|
__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:sw=4:et:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from .errors import Error
TRUE = true = True
FALSE = false = False
__all__ = ['Option', 'Options', 'ANYTYPE']
class ANYTYPE(object):
""" Dummy class to signal any value
"""
pass
# ----------------------------------------------------------------------
# Exception for duplicated Options
# ----------------------------------------------------------------------
class DuplicatedOptionError(Error):
def __init__(self, option_name):
self.option = option_name
def __str__(self):
return "Option '%s' already defined" % self.option
class UndefinedOptionError(Error):
def __init__(self, option_name):
self.option = option_name
def __str__(self):
return "Undefined option '%s'" % self.option
class OptionStackUnderflowError(Error):
def __init__(self, option_name):
self.option = option_name
def __str__(self):
return "Cannot pop option '%s'. Option stack is empty" % self.option
class InvalidValueError(Error):
def __init__(self, option_name, _type, value):
self.option = option_name
self.value = value
self.type = _type
def __str__(self):
return "Invalid value '%s' for option '%s'. Value type must be '%s'" \
% (self.value, self.option, self.type)
# ----------------------------------------------------------------------
# This class interfaces an Options Container
# ----------------------------------------------------------------------
class Option(object):
""" A simple container
"""
def __init__(self, name, type_, value=None):
self.name = name
self.type = type_
self.value = value
self.stack = [] # An option stack
@property
def value(self):
return self.__value
@value.setter
def value(self, value):
if self.type is not None and not isinstance(value, self.type):
try:
value = eval(value)
except TypeError:
pass
except ValueError:
pass
if value is not None and not isinstance(value, self.type):
raise InvalidValueError(self.name, self.type, value)
self.__value = value
def push(self, value=None):
if value is None:
value = self.value
self.stack.append(self.value)
self.value = value
def pop(self):
result = self.value
try:
self.value = self.stack.pop()
except IndexError:
raise OptionStackUnderflowError(self.name)
return result
# ----------------------------------------------------------------------
# This class interfaces an Options Container
# ----------------------------------------------------------------------
class Options(object):
def __init__(self):
self.options = None
self.reset()
def reset(self):
if self.options is None:
self.options = {}
for opt in list(self.options.keys()): # converts to list since dict will change size during iteration
self.remove_option(opt)
def add_option(self, name, type_=None, default_value=None):
if name in self.options.keys():
raise DuplicatedOptionError(name)
if type_ is None and default_value is not None:
type_ = type(default_value)
elif type_ is ANYTYPE:
type_ = None
self.options[name] = Option(name, type_, default_value)
setattr(self, name, self.options[name])
def has_option(self, name):
""" Returns whether the given option is defined in this class.
"""
return hasattr(self, name)
def add_option_if_not_defined(self, name, type_=None, default_value=None):
if self.has_option(name):
return
self.add_option(name, type_, default_value)
def remove_option(self, name):
if name not in self.options.keys():
raise UndefinedOptionError(name)
del self.options[name]
delattr(self, name)
def option(self, name):
if name not in self.options.keys():
raise UndefinedOptionError(name)
return self.options[name]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/options.py
|
options.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Floating point converter
def fp(x):
""" Returns a floating point number as EXP+128, Mantissa
"""
def bin32(f):
""" Returns ASCII representation for a 32 bit integer value
"""
result = ''
a = int(f) & 0xFFFFFFFF # ensures int 32
for i in range(32):
result = str(a % 2) + result
a = a >> 1
return result
def bindec32(f):
""" Returns binary representation of a mantissa x (x is float)
"""
result = '0'
a = f
if f >= 1:
result = bin32(f)
result += '.'
c = int(a)
for i in range(32):
a -= c
a *= 2
c = int(a)
result += str(c)
return result
e = 0 # exponent
s = 1 if x < 0 else 0 # sign
m = abs(x) # mantissa
while m >= 1:
m /= 2.0
e += 1
while 0 < m < 0.5:
m *= 2.0
e -= 1
M = bindec32(m)[3:]
M = str(s) + M
E = bin32(e + 128)[-8:] if x != 0 else bin32(0)[-8:]
return M, E
def immediate_float(x):
""" Returns C DE HL as values for loading
and immediate floating point.
"""
def bin2hex(y):
return "%02X" % int(y, 2)
M, E = fp(x)
C = '0' + bin2hex(E) + 'h'
ED = '0' + bin2hex(M[8:16]) + bin2hex(M[:8]) + 'h'
LH = '0' + bin2hex(M[24:]) + bin2hex(M[16:24]) + 'h'
return C, ED, LH
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/api/fp.py
|
fp.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/parsetab/__init__.py
|
__init__.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from typing import Optional
import collections
from api.errors import Error
__all__ = ['NotAnAstError', 'Tree']
class NotAnAstError(Error):
""" Thrown when the "pointer" is not
an AST, but another thing.
"""
def __init__(self, instance):
self.instance = instance
self.msg = "Object '%s' is not an Ast instance" % str(instance)
def __str__(self):
return self.msg
class Tree:
""" Simple tree implementation
"""
parent: Optional['Tree'] = None
class ChildrenList:
def __init__(self, node: 'Tree'):
assert isinstance(node, Tree)
self.parent = node # Node having this children
self._children = []
def __getitem__(self, key):
if isinstance(key, int):
return self._children[key]
result = Tree.ChildrenList(self.parent)
for x in self._children[key]:
result.append(x)
return result
def __setitem__(self, key, value):
assert value is None or isinstance(value, Tree)
if value is not None:
value.parent = self.parent
self._children[key] = value
def __delitem__(self, key):
self._children[key].parent = None
del self._children[key]
def append(self, value):
assert isinstance(value, Tree)
value.parent = self.parent
self._children.append(value)
def insert(self, pos, value):
assert isinstance(value, Tree)
value.parent = self.parent
self._children.insert(pos, value)
def pop(self, pos=-1):
result = self._children.pop(pos)
result.parent = None
return result
def __len__(self):
return len(self._children)
def __add__(self, other):
if not isinstance(other, Tree.ChildrenList):
assert isinstance(other, collections.Container)
result = Tree.ChildrenList(self.parent)
for x in self:
result.append(x)
for x in other:
result.append(x)
return result
def __repr__(self):
return "%s:%s" % (self.parent.__repr__(), str([x.__repr__() for x in self._children]))
def __init__(self):
self._children = Tree.ChildrenList(self)
@property
def children(self):
return self._children
@children.setter
def children(self, value):
assert isinstance(value, collections.Iterable)
while len(self.children):
self.children.pop()
self._children = Tree.ChildrenList(self)
for x in value:
self.children.append(x)
def inorder(self):
""" Traverses the tree in order
"""
for i in self.children:
yield from i.inorder()
yield self
def preorder(self):
""" Traverses the tree in preorder
"""
yield self
for i in self.children:
yield from i.preorder()
def postorder(self):
""" Traverses the tree in postorder
"""
for i in range(len(self.children) - 1, -1, -1):
yield from self.children[i].postorder()
yield self
def appendChild(self, node):
""" Appends the given node to the current children list
"""
self.children.append(node)
def prependChild(self, node):
""" Inserts the given node at the beginning of the children list
"""
self.children.insert(0, node)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/ast_/tree.py
|
tree.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
# ----------------------------------------------------------------------
from typing import Callable, Any
import types
from .tree import Tree
# ----------------------------------------------------------------------
# Abstract Syntax Tree class
# ----------------------------------------------------------------------
class Ast(Tree):
""" Adds some methods for easier coding...
"""
pass
class NodeVisitor:
def visit(self, node):
stack = [node]
last_result = None
while stack:
try:
last = stack[-1]
if isinstance(last, types.GeneratorType):
stack.append(last.send(last_result))
last_result = None
elif isinstance(last, Ast):
stack.append(self._visit(stack.pop()))
else:
last_result = stack.pop()
except StopIteration:
stack.pop()
return last_result
def _visit(self, node):
methname = 'visit_' + node.token
meth = getattr(self, methname, None)
if meth is None:
meth = self.generic_visit
return meth(node)
@staticmethod
def generic_visit(node: Ast):
raise RuntimeError("No {}() method defined".format('visit_' + node.token))
def filter_inorder(self, node, filter_func: Callable[[Any], bool]):
""" Visit the tree inorder, but only those that return true for filter
"""
stack = [node]
while stack:
node = stack.pop()
if filter_func(node):
yield self.visit(node)
elif isinstance(node, Ast):
stack.extend(node.children[::-1])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/ast_/ast.py
|
ast.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .ast import Ast
from .ast import NodeVisitor
from .ast import types
from .tree import Tree
__all__ = [
'Ast',
'NodeVisitor',
'types',
'Tree',
]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/ast_/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------------
# KopyLeft (K) 2008
# by Jose M. Rodriguez de la Rosa
#
# This program is licensed under the
# GNU Public License v.3.0
#
# The code emission interface.
# --------------------------------------------
from .codeemitter import CodeEmitter
class BinaryEmitter(CodeEmitter):
""" Writes compiled code as raw binary data.
"""
def emit(self, output_filename, program_name, loader_bytes, entry_point,
program_bytes, aux_bin_blocks, aux_headless_bin_blocks):
""" Emits resulting binary file.
"""
with open(output_filename, 'wb') as f:
f.write(bytearray(program_bytes))
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/outfmt/binary.py
|
binary.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------------
# KopyLeft (K) 2008
# by Jose M. Rodriguez de la Rosa
#
# This program is licensed under the
# GNU Public License v.3.0
#
# Simple .tzx file library
# Only supports standard headers by now.
# --------------------------------------------
from .codeemitter import CodeEmitter
class TZX(CodeEmitter):
""" Class to represent tzx data
"""
VERSION_MAJOR = 1
VERSION_MINOR = 21
# Some interesting constants
# TZX BLOCK TYPES
BLOCK_STANDARD = 0x10
# ZX Spectrum BLOCK Types
BLOCK_TYPE_HEADER = 0
BLOCK_TYPE_DATA = 0xFF
# ZX Spectrum BASIC / ARRAY / CODE types
HEADER_TYPE_BASIC = 0
HEADER_TYPE_NUMBER_ARRAY = 1
HEADER_TYPE_CHAR_ARRAY = 2
HEADER_TYPE_CODE = 3
def __init__(self):
""" Initializes the object with standard header
"""
self.output = bytearray(b'ZXTape!')
self.out(0x1A)
self.out([self.VERSION_MAJOR, self.VERSION_MINOR])
def LH(self, value):
""" Return a 16 bytes value as a list of 2 bytes [Low, High]
"""
valueL = value & 0x00FF # Low byte
valueH = (value & 0xFF00) >> 8 # High byte
return [valueL, valueH]
def out(self, l):
""" Adds a list of bytes to the output string
"""
if not isinstance(l, list):
l = [l]
self.output.extend([int(i) & 0xFF for i in l])
def standard_block(self, _bytes):
""" Adds a standard block of bytes
"""
self.out(self.BLOCK_STANDARD) # Standard block ID
self.out(self.LH(1000)) # 1000 ms standard pause
self.out(self.LH(len(_bytes) + 1)) # + 1 for CHECKSUM byte
checksum = 0
for i in _bytes:
checksum ^= (int(i) & 0xFF)
self.out(i)
self.out(checksum)
def dump(self, fname):
""" Saves TZX file to fname
"""
with open(fname, 'wb') as f:
f.write(self.output)
def save_header(self, _type, title, length, param1, param2):
""" Saves a generic standard header:
type: 00 -- Program
01 -- Number Array
02 -- Char Array
03 -- Code
title: Name title.
Will be truncated to 10 chars and padded
with spaces if necessary.
length: Data length (in bytes) of the next block.
param1: For CODE -> Start address.
For PROGRAM -> Autostart line (>=32768 for no autostart)
For DATA (02 & 03) high byte of param1 have the variable name.
param2: For CODE -> 32768
For PROGRAM -> Start of the Variable area relative to program Start (Length of basic in bytes)
For DATA (02 & 03) NOT USED
Info taken from: http://www.worldofspectrum.org/faq/reference/48kreference.htm#TapeDataStructure
"""
title = (title + 10 * ' ')[:10] # Padd it with spaces
title_bytes = [ord(i) for i in title] # Convert it to bytes
_bytes = [self.BLOCK_TYPE_HEADER, _type] + title_bytes + self.LH(length) + self.LH(param1) + self.LH(param2)
self.standard_block(_bytes)
def standard_bytes_header(self, title, addr, length):
""" Generates a standard header block of CODE type
"""
self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768)
def standard_program_header(self, title, length, line=32768):
""" Generates a standard header block of PROGRAM type
"""
self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
def save_code(self, title, addr, _bytes):
""" Saves the given bytes as code. If bytes are strings,
its chars will be converted to bytes
"""
self.standard_bytes_header(title, addr, len(_bytes))
_bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates to bytes
self.standard_block(_bytes)
def save_program(self, title, bytes, line=32768):
""" Saves the given bytes as a BASIC program.
"""
self.standard_program_header(title, len(bytes), line)
bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes] # & 0xFF truncates to bytes
self.standard_block(bytes)
def emit(self, output_filename, program_name, loader_bytes, entry_point,
program_bytes, aux_bin_blocks, aux_headless_bin_blocks):
""" Emits resulting tape file.
"""
if loader_bytes is not None:
self.save_program('loader', loader_bytes, line=1) # Put line 0 to protect against MERGE
self.save_code(program_name, entry_point, program_bytes)
for name, block in aux_bin_blocks:
self.save_code(name, 0, block)
for block in aux_headless_bin_blocks:
self.standard_block(block)
self.dump(output_filename)
if __name__ == '__main__':
""" Sample test if invoked from command line
"""
t = TZX()
t.save_code('tzxtest', 16384, range(255))
t.dump('tzxtest.tzx')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/outfmt/tzx.py
|
tzx.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------------
# KopyLeft (K) 2008
# by Jose M. Rodriguez de la Rosa
#
# This program is licensed under the
# GNU Public License v.3.0
#
# The code emission interface.
# --------------------------------------------
class CodeEmitter(object):
""" The base code emission interface.
"""
pass
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/outfmt/codeemitter.py
|
codeemitter.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .binary import BinaryEmitter
from .codeemitter import CodeEmitter
from .tzx import TZX
from .tap import TAP
__all__ = [
'BinaryEmitter',
'CodeEmitter',
'TZX',
'TAP',
]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/outfmt/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------------
# KopyLeft (K) 2008
# by Jose M. Rodriguez de la Rosa
#
# This program is licensed under the
# GNU Public License v.3.0
#
# Simple .tap file library
# Only supports standard headers by now.
# --------------------------------------------
from .tzx import TZX
class TAP(TZX):
""" Derived from TZX. Implements TAP output
"""
def __init__(self):
"""Initializes the object with standard header
"""
super(TAP, self).__init__()
self.output = bytearray() # Restarts the output
def standard_block(self, bytes_):
"""Adds a standard block of bytes. For TAP files, it's just the
Low + Hi byte plus the content (here, the bytes plus the checksum)
"""
self.out(self.LH(len(bytes_) + 1)) # + 1 for CHECKSUM byte
checksum = 0
for i in bytes_:
checksum ^= (int(i) & 0xFF)
self.out(i)
self.out(checksum)
if __name__ == '__main__':
"""Sample test if invoked from command line
"""
t = TAP()
t.save_code('taptest', 16384, range(255))
t.dump('tzxtest.tap')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/outfmt/tap.py
|
tap.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.insert(0, path)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from api.constants import TYPE
from symbols.type_ import SymbolBASICTYPE
from symbols.type_ import Type
class TestSymbolBASICTYPE(TestCase):
def test_size(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
self.assertEqual(t.size, TYPE.size(type_))
def test_is_basic(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
self.assertTrue(t.is_basic)
def test_is_dynamic(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
self.assertTrue((type_ == TYPE.string) == t.is_dynamic)
def test__eq__(self):
for t_ in TYPE.types:
t = SymbolBASICTYPE(t_)
self.assertTrue(t == t) # test same reference
for t_ in TYPE.types:
t1 = SymbolBASICTYPE(t_)
t2 = SymbolBASICTYPE(t_)
self.assertTrue(t1 == t2)
t = SymbolBASICTYPE(TYPE.string)
self.assertEqual(t, Type.string)
def test__ne__(self):
for t1_ in TYPE.types:
t1 = SymbolBASICTYPE(t1_)
for t2_ in TYPE.types:
t2 = SymbolBASICTYPE(t2_)
if t1 == t2: # Already validated
self.assertTrue(t1 == t2)
else:
self.assertTrue(t1 != t2)
def test_to_signed(self):
for type_ in TYPE.types:
if type_ is TYPE.unknown or type_ == TYPE.string:
continue
t = SymbolBASICTYPE(type_)
q = t.to_signed()
self.assertTrue(q.is_signed)
def test_bool(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
if t.type_ == TYPE.unknown:
self.assertFalse(t)
else:
self.assertTrue(t)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolBASICTYPE.py
|
test_symbolBASICTYPE.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
import symbols
class TestSymbolSENTENCE(TestCase):
def setUp(self):
self.TOKEN = 'TOKEN'
def test_args(self):
# Must allow None args (which will be ignored)
s = symbols.SENTENCE(self.TOKEN, None, None, symbols.SENTENCE(self.TOKEN), None)
self.assertEqual(len(s.args), 1)
def test_args_fail(self):
# Fails for non symbol args
self.assertRaises(AssertionError, symbols.SENTENCE, self.TOKEN, 'blah')
def test_token(self):
s = symbols.SENTENCE(self.TOKEN)
self.assertEqual(s.token, self.TOKEN)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolSENTENCE.py
|
test_symbolSENTENCE.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import api.global_ as gl
import api.symboltable
from symbols import FUNCDECL
from symbols.type_ import Type
class TestSymbolFUNCDECL(TestCase):
def setUp(self):
api.global_.SYMBOL_TABLE = api.symboltable.SymbolTable()
self.f = gl.SYMBOL_TABLE.declare_func('f', 1, type_=Type.ubyte)
self.s = FUNCDECL(self.f, 1)
def test__init__fail(self):
self.assertRaises(AssertionError, FUNCDECL, 'bla', 1)
def test_entry__getter(self):
self.assertEqual(self.s.entry, self.f)
def test_entry__setter(self):
self.s.entry = tmp = gl.SYMBOL_TABLE.declare_func('q', 1)
self.assertEqual(self.s.entry, tmp)
def test_entry_fail__(self):
self.assertRaises(AssertionError, FUNCDECL.entry.fset, self.s, 'blah')
def test_name(self):
self.assertEqual(self.s.name, 'f')
def test_locals_size(self):
self.assertEqual(self.s.locals_size, 0)
def test_local_symbol_table(self):
self.assertIsNone(self.s.local_symbol_table)
def test_local_symbol_table__setter_fail(self):
self.assertRaises(AssertionError, FUNCDECL.local_symbol_table.fset, self.s, 'blah')
def test_type_(self):
self.assertEqual(self.s.type_, Type.ubyte)
def test_size(self):
self.assertEqual(self.s.type_.size, Type.ubyte.size)
def test_mangled_(self):
self.assertEqual(self.s.mangled, '_f')
def test_make_node(self):
f = FUNCDECL.make_node('f', 1)
self.assertIsNotNone(f)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolFUNCDECL.py
|
test_symbolFUNCDECL.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
import api.global_ as gl
from api.constants import TYPE
from api.constants import CLASS
from symbols.type_ import Type
import symbols
import functools
class TestSymbolVARARRAY(TestCase):
def setUp(self):
l1 = 1
l2 = 2
l3 = 3
l4 = 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
self.bounds = symbols.BOUNDLIST.make_node(None, b, c)
def test__init__fail(self):
self.assertRaises(AssertionError, symbols.VARARRAY, 'test', 'blahblah', 2)
def test__init__(self):
arr = symbols.VARARRAY('test', self.bounds, 1, type_=Type.ubyte)
self.assertEqual(arr.class_, CLASS.array)
self.assertEqual(arr.type_, Type.ubyte)
def test_bounds(self):
arr = symbols.VARARRAY('test', self.bounds, 1)
self.assertEqual(arr.bounds, self.bounds)
def test_count(self):
arr = symbols.VARARRAY('test', self.bounds, 1)
self.assertEqual(arr.count, functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds)))
def test_size(self):
arr = symbols.VARARRAY('test', self.bounds, 1, type_=Type.ubyte)
self.assertEqual(arr.size, arr.type_.size * arr.count)
def test_memsize(self):
arr = symbols.VARARRAY('test', self.bounds, 1, type_=Type.ubyte)
self.assertEqual(arr.memsize, 2 * TYPE.size(gl.PTR_TYPE))
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolVARARRAY.py
|
test_symbolVARARRAY.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from api.constants import TYPE
from symbols.type_ import SymbolTYPE
from symbols.type_ import SymbolBASICTYPE
from symbols.type_ import SymbolTYPEREF
from symbols.type_ import Type
class TestSymbolTYPE(TestCase):
def test__eq__(self):
for t1_ in TYPE.types:
t1 = SymbolBASICTYPE(t1_)
for t2_ in TYPE.types:
t2 = SymbolBASICTYPE(t2_)
t = SymbolTYPE('test_type', 0, t1, t2)
tt = SymbolTYPE('other_type', 0, t)
self.assertTrue(t == t)
self.assertFalse(t != t)
self.assertFalse(tt == t)
self.assertFalse(t == tt)
self.assertTrue(tt == tt)
self.assertFalse(tt != tt)
self.assertTrue(t != tt)
self.assertTrue(tt != t)
def test_is_basic(self):
for t1_ in TYPE.types:
t1 = SymbolBASICTYPE(t1_)
for t2_ in TYPE.types:
t2 = SymbolBASICTYPE(t2_)
t = SymbolTYPE('test_type', 0, t1, t2)
self.assertFalse(t.is_basic)
def test_is_alias(self):
for t1_ in TYPE.types:
t1 = SymbolBASICTYPE(t1_)
for t2_ in TYPE.types:
t2 = SymbolBASICTYPE(t2_)
t = SymbolTYPE('test_type', 0, t1, t2)
self.assertFalse(t.is_alias)
def test_size(self):
for t1_ in TYPE.types:
t1 = SymbolBASICTYPE(t1_)
for t2_ in TYPE.types:
t2 = SymbolBASICTYPE(t2_)
t = SymbolTYPE('test_type', 0, t1, t2)
self.assertEqual(t.size, t1.size + t2.size)
def test_cmp_types(self):
""" Test == operator for different types
"""
tr = SymbolTYPEREF(Type.unknown, 0)
self.assertTrue(tr == Type.unknown)
self.assertRaises(AssertionError, tr.__eq__, TYPE.unknown)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolTYPE.py
|
test_symbolTYPE.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from six import StringIO
import arch.zx48k # noqa initializes arch
import symbols
import api.global_ as gl
import api.config as config
from api.symboltable import SymbolTable
from symbols.type_ import Type
from libzxbpp import zxbpp
class TestSymbolARRAYACCESS(TestCase):
def setUp(self):
zxbpp.init()
l1 = 1
l2 = 2
l3 = 3
l4 = 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
self.bounds = symbols.BOUNDLIST.make_node(None, b, c)
self.arr = symbols.VARARRAY('test', self.bounds, 1, type_=Type.ubyte)
self.arg = symbols.ARGLIST(symbols.ARGUMENT(symbols.NUMBER(2, 1, type_=Type.uinteger), 1),
symbols.ARGUMENT(symbols.NUMBER(3, 1, type_=Type.uinteger), 1))
gl.SYMBOL_TABLE = SymbolTable()
# Clears stderr and prepares for capturing it
config.OPTIONS.remove_option('stderr')
config.OPTIONS.add_option('stderr', None, StringIO())
config.OPTIONS.add_option_if_not_defined('explicit', None, False)
@property
def OUTPUT(self):
return config.OPTIONS.stderr.value.getvalue()
def test__init__(self):
aa = symbols.ARRAYACCESS(self.arr, self.arg, 2)
self.assertIsInstance(aa, symbols.ARRAYACCESS)
def test__init__fail(self):
# First argument must be an instance of VARARRAY
self.assertRaises(AssertionError, symbols.ARRAYACCESS, 'bla', self.arg, 2)
def test_entry__getter(self):
aa = symbols.ARRAYACCESS(self.arr, self.arg, 2)
self.assertIs(aa.entry, self.arr)
def test_entry__setter(self):
aa = symbols.ARRAYACCESS(self.arr, self.arg, 2)
ar2 = symbols.VARARRAY('test2', self.bounds, 1, type_=Type.ubyte)
aa.entry = ar2
self.assertIs(aa.entry, ar2)
def test_entry__setter_fail(self):
# entry must be an instance of VARARRAY
aa = symbols.ARRAYACCESS(self.arr, self.arg, 2)
self.assertRaises(AssertionError, symbols.ARRAYACCESS.entry.fset, aa, 'blah')
def test_scope(self):
aa = symbols.ARRAYACCESS(self.arr, self.arg, 2)
self.assertEqual(aa.scope, self.arr.scope)
def test_make_node(self):
gl.SYMBOL_TABLE.declare_array('test', 1, symbols.TYPEREF(self.arr.type_, 1),
bounds=self.bounds)
aa = symbols.ARRAYACCESS.make_node('test', self.arg, lineno=2)
self.assertIsInstance(aa, symbols.ARRAYACCESS)
def test_make_node_fail(self):
gl.SYMBOL_TABLE.declare_array('test', 1, symbols.TYPEREF(self.arr.type_, 1),
bounds=self.bounds)
self.arg = symbols.ARGLIST(symbols.ARGUMENT(symbols.NUMBER(2, 1), 1))
aa = symbols.ARRAYACCESS.make_node('test', self.arg, lineno=2)
self.assertIsNone(aa)
self.assertEqual(self.OUTPUT, "(stdin):2: error: Array 'test' has 2 dimensions, not 1\n")
def test_make_node_warn(self):
gl.SYMBOL_TABLE.declare_array('test', 1, symbols.TYPEREF(self.arr.type_, 1),
bounds=self.bounds)
self.arg[1] = symbols.ARGUMENT(symbols.NUMBER(9, 1), 1)
aa = symbols.ARRAYACCESS.make_node('test', self.arg, lineno=2)
self.assertIsNotNone(aa)
self.assertEqual(self.OUTPUT, "(stdin):2: warning: Array 'test' subscript out of range\n")
def test_offset(self):
gl.SYMBOL_TABLE.declare_array('test', 1, symbols.TYPEREF(self.arr.type_, 1),
bounds=self.bounds)
aa = symbols.ARRAYACCESS.make_node('test', self.arg, lineno=2)
self.assertIsInstance(aa, symbols.ARRAYACCESS)
self.assertIsNotNone(aa.offset)
self.assertEqual(aa.offset, 2)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolARRAYACCESS.py
|
test_symbolARRAYACCESS.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from symbols import TYPECAST
from symbols import NUMBER
from symbols import VAR
from symbols.type_ import Type
from api.config import OPTIONS
from six import StringIO
from api.constants import CLASS
from libzxbpp import zxbpp
__autor__ = 'boriel'
class TestSymbolTYPECAST(TestCase):
def setUp(self):
zxbpp.init()
self.t = TYPECAST(Type.float_, NUMBER(3, lineno=1), lineno=2)
if OPTIONS.has_option('stderr'):
OPTIONS.remove_option('stderr')
OPTIONS.add_option('stderr', type_=None, default_value=StringIO())
def test_operand(self):
self.assertEqual(self.t.operand, 3)
self.assertEqual(self.t.type_, Type.float_)
self.assertEqual(self.t.operand.type_, Type.ubyte)
def test_make_node__nochange(self):
n = NUMBER(3, 1, type_=Type.float_)
self.assertIs(TYPECAST.make_node(Type.float_, n, 1), n)
def test_operand_setter(self):
self.t.operand = NUMBER(2, lineno=1)
self.assertEqual(self.t.operand, 2)
def test_operand_setter_fail(self):
self.assertRaises(AssertionError, TYPECAST.operand.fset, self.t, 3)
def test_make_node(self):
t = TYPECAST.make_node(Type.float_, NUMBER(3, lineno=1), lineno=2)
# t is a constant, so typecast is done on the fly
self.assertEqual(t.type_, Type.float_)
self.assertEqual(t, self.t.operand)
def test_make_const(self):
""" Must return a number
"""
v = VAR('a', lineno=1, type_=Type.byte_)
v.default_value = 3
v.class_ = CLASS.const
t = TYPECAST.make_node(Type.float_, v, lineno=2)
self.assertIsInstance(t, NUMBER)
self.assertEqual(t, 3)
def test_make_node_None(self):
""" None is allowed as operand
"""
self.assertIsNone(TYPECAST.make_node(Type.float_, None, lineno=2))
def test_make_node_fail_type(self):
self.assertRaises(AssertionError, TYPECAST.make_node, 'blah', NUMBER(3, lineno=1), lineno=2)
def test_make_node_fail_oper(self):
self.assertRaises(AssertionError, TYPECAST.make_node, Type.float_, 'bla', lineno=2)
def test_make_node_loose_byte(self):
TYPECAST.make_node(Type.byte_, NUMBER(256, lineno=1), lineno=2)
self.assertEqual(self.OUTPUT, "(stdin):1: warning: Conversion may lose significant digits\n")
def test_make_node_loose_byte2(self):
TYPECAST.make_node(Type.byte_, NUMBER(3.5, lineno=1), lineno=2)
self.assertEqual(self.OUTPUT, "(stdin):1: warning: Conversion may lose significant digits\n")
def test_make_node_loose_byte3(self):
TYPECAST.make_node(Type.ubyte, NUMBER(-3, lineno=1), lineno=2)
self.assertEqual(self.OUTPUT, '')
def test_make_node_loose_byte4(self):
TYPECAST.make_node(Type.ubyte, NUMBER(-257, lineno=1), lineno=2)
self.assertEqual(self.OUTPUT, "(stdin):1: warning: Conversion may lose significant digits\n")
@property
def OUTPUT(self):
return OPTIONS.stderr.value.getvalue()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolTYPECAST.py
|
test_symbolTYPECAST.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from six import StringIO
from api.config import OPTIONS
import symbols
from symbols.type_ import Type
from libzxbpp import zxbpp
class TestSymbolBINARY(TestCase):
def setUp(self):
zxbpp.init()
self.l = symbols.VAR('a', lineno=1, type_=Type.ubyte)
self.r = symbols.NUMBER(3, lineno=2)
self.b = symbols.BINARY('PLUS', self.l, self.r, lineno=3)
self.st = symbols.STRING("ZXBASIC", lineno=1)
if OPTIONS.has_option('stderr'):
OPTIONS.remove_option('stderr')
OPTIONS.add_option('stderr', type_=None, default_value=StringIO())
def test_left_getter(self):
self.assertEqual(self.b.left, self.l)
def test_left_setter(self):
self.b.left = self.r
self.assertEqual(self.b.left, self.r)
def test_right_getter(self):
self.assertEqual(self.b.right, self.r)
def test_right_setter(self):
self.b.right = self.l
self.assertEqual(self.b.right, self.l)
def test_size(self):
self.assertEqual(self.b.size, self.b.type_.size)
def test_make_node_None(self):
''' Makes a binary with 2 constants, not specifying
the lambda function.
'''
symbols.BINARY.make_node('PLUS', self.r, self.r, lineno=1)
def test_make_node_PLUS(self):
''' Makes a binary with 2 constants, specifying
the lambda function.
'''
n = symbols.BINARY.make_node('PLUS', self.r, self.r, lineno=1, func=lambda x, y: x + y)
self.assertIsInstance(n, symbols.NUMBER)
self.assertEqual(n, 6)
def test_make_node_PLUS_STR(self):
''' Makes a binary with 2 constants, specifying
the lambda function.
'''
n = symbols.BINARY.make_node('PLUS', self.r, self.st, lineno=1, func=lambda x, y: x + y)
self.assertIsNone(n)
self.assertEqual(self.OUTPUT, '(stdin):1: error: Cannot convert string to a value. Use VAL() function\n')
def test_make_node_PLUS_STR2(self):
''' Makes a binary with 2 constants, specifying
the lambda function.
'''
n = symbols.BINARY.make_node('PLUS', self.st, self.st, lineno=1, func=lambda x, y: x + y)
self.assertEqual(n.value, self.st.value * 2)
@property
def OUTPUT(self):
return OPTIONS.stderr.value.getvalue()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolBINARY.py
|
test_symbolBINARY.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
import api.global_ as gl
class TestSymbolSTRSLICE(TestCase):
def setUp(self):
STR = "ZXBASIC"
self.str_ = symbols.STRING(STR, 1)
self.lower = symbols.NUMBER(1, 1, type_=gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE])
self.upper = symbols.NUMBER(2, 1, type_=gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE])
def test__init__(self):
symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
def test_string__getter(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
self.assertEqual(s.string, self.str_)
def test_string__setter(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
tmp = symbols.STRING(self.str_.value * 2, 1)
s.string = tmp
self.assertEqual(s.string, tmp)
def test_string__setter_fail(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
self.assertRaises(AssertionError, symbols.STRSLICE.string.fset, s, 0)
def test_lower(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
self.assertEqual(s.lower, self.lower)
def test_lower__setter(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
s.lower = symbols.NUMBER(44, 1, type_=gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE])
self.assertEqual(s.lower, 44)
def test_upper(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
self.assertEqual(s.upper, self.upper)
def test_upper__setter(self):
s = symbols.STRSLICE(self.str_, self.lower, self.upper, 1)
s.upper = symbols.NUMBER(44, 1, type_=gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE])
self.assertEqual(s.upper, 44)
def test_make_node(self):
s = symbols.STRSLICE.make_node(1, self.str_, self.lower, self.upper)
self.assertIsInstance(s, symbols.STRING)
self.assertEqual(s.value, 'XB')
def test_make_node_wrong(self):
bad_index = symbols.VAR('a', 0, type_=gl.SYMBOL_TABLE.basic_types[gl.TYPE.string])
s = symbols.STRSLICE.make_node(1, self.str_, bad_index, bad_index)
self.assertIsNone(s)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolSTRSLICE.py
|
test_symbolSTRSLICE.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
class TestSymbolBOUNDLIST(TestCase):
def test_make_node(self):
l1 = 1
l2 = 2
l3 = 3
l4 = 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
symbols.BOUNDLIST.make_node(None, b, c)
def test__str__(self):
l1 = 1
l2 = 2
l3 = 3
l4 = 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
a = symbols.BOUNDLIST.make_node(None, b, c)
self.assertEqual(str(a), '(({} TO {}), ({} TO {}))'.format(l1, l2, l3, l4))
def test__len__(self):
l1 = 1
l2 = 2
l3 = 3
l4 = 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
a = symbols.BOUNDLIST(b, c)
self.assertEqual(len(a), 2)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolBOUNDLIST.py
|
test_symbolBOUNDLIST.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
class TestSymbolARGLIST(TestCase):
def setUp(self):
self.VALUE = 5
self.value = symbols.NUMBER(self.VALUE, 1)
self.a = symbols.ARGLIST(symbols.ARGUMENT(symbols.NUMBER(self.VALUE, 1), 1))
def test__len__(self):
self.assertEqual(len(self.a), 1)
b = symbols.ARGLIST()
self.assertEqual(len(b), 0)
def test_args(self):
self.assertEqual(self.a[0], self.value)
def test_args_setter(self):
self.a[0] = symbols.ARGUMENT(symbols.NUMBER(self.VALUE + 1, 1), 1)
self.assertEqual(self.a[0], self.value + 1)
def test_args_setter_fail(self):
self.assertRaises(AssertionError, symbols.ARGLIST.__setitem__, self.a, 0, 'blah')
def test_make_node_empty(self):
b = symbols.ARGLIST.make_node(None)
self.assertIsInstance(b, symbols.ARGLIST)
self.assertEqual(len(b), 0)
def test_make_node_single(self):
b = symbols.ARGLIST.make_node(symbols.ARGUMENT(symbols.NUMBER(self.VALUE, 1), 1))
self.assertIsInstance(b, symbols.ARGLIST)
self.assertEqual(len(b), 1)
self.assertEqual(b[0], self.value)
def test_make_node_single2(self):
b = symbols.ARGLIST.make_node(None, symbols.ARGUMENT(symbols.NUMBER(self.VALUE, 1), 1))
self.assertIsInstance(b, symbols.ARGLIST)
self.assertEqual(len(b), 1)
self.assertEqual(b[0], self.value)
def test_make_node_fails(self):
self.assertRaises(AssertionError, symbols.ARGLIST.make_node, 'blah')
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolARGLIST.py
|
test_symbolARGLIST.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
from symbols.type_ import Type
from api.constants import SCOPE
from api.constants import KIND
from api.constants import CLASS
class TestSymbolVAR(TestCase):
def setUp(self):
self.v = symbols.VAR('v', 1) # This also tests __init__
def test__init__fail(self):
self.assertRaises(AssertionError, symbols.VAR, 'v', 1, None, 'blah') # type_='blah'
def test_size(self):
self.assertIsNone(self.v.type_)
self.v.type_ = Type.byte_
self.assertEqual(self.v.type_, Type.byte_)
def test_kind(self):
self.assertEqual(self.v.kind, KIND.var)
def test_set_kind(self):
self.v.set_kind(KIND.function, 2)
self.assertEqual(self.v.kind, KIND.function)
def test_set_kind_fail(self):
self.assertRaises(AssertionError, self.v.set_kind, 'blah', 2)
def test_add_alias(self):
self.v.add_alias(self.v)
def test_add_alias_fail(self):
self.assertRaises(AssertionError, self.v.add_alias, 'blah')
def test_set_value(self):
self.v.set_kind(KIND.var, 1)
self.v.class_ = CLASS.const
self.v.value = 1234
self.assertEqual(self.v.value, 1234)
def test_set_value_var(self):
self.v.set_kind(KIND.var, 1)
self.v.class_ = CLASS.var
self.assertRaises(AssertionError, getattr, self.v, 'value')
def test_is_aliased(self):
self.assertFalse(self.v.is_aliased)
self.v.add_alias(self.v)
self.assertTrue(self.v.is_aliased)
def test_t(self):
self.assertEqual(self.v.scope, SCOPE.global_) # Must be initialized as global_
self.assertEqual(self.v.t, self.v.mangled)
self.v.scope = SCOPE.local
self.assertEqual(self.v.t, self.v._t)
self.v.class_ = CLASS.const
self.v.default_value = 54321
self.assertEqual(self.v.t, '54321')
def test_type_(self):
self.v.type_ = Type.byte_
self.assertEqual(self.v.type_, Type.byte_)
def test_type_fail(self):
self.assertRaises(AssertionError, symbols.VAR.type_.fset, self.v, 'blah')
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolVAR.py
|
test_symbolVAR.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from api.constants import TYPE
from symbols import NUMBER
from symbols import BASICTYPE
from symbols import CONST
class TestSymbolNUMBER(TestCase):
def test__init__(self):
self.assertRaises(AssertionError, NUMBER, 0, lineno=None)
self.assertRaises(AssertionError, NUMBER, 0, lineno=1, type_='')
n = NUMBER(0, lineno=1)
self.assertEqual(n.type_, BASICTYPE(TYPE.ubyte))
n = NUMBER(-1, lineno=1)
self.assertEqual(n.type_, BASICTYPE(TYPE.byte_))
n = NUMBER(256, lineno=1)
self.assertEqual(n.type_, BASICTYPE(TYPE.uinteger))
n = NUMBER(-256, lineno=1)
self.assertEqual(n.type_, BASICTYPE(TYPE.integer))
def test__cmp__(self):
n = NUMBER(0, lineno=1)
m = NUMBER(1, lineno=2)
self.assertNotEqual(n, m)
self.assertEqual(n, n)
self.assertNotEqual(n, 2)
self.assertEqual(n, 0)
self.assertGreater(n, -1)
self.assertLess(n, 1)
self.assertGreater(m, n)
self.assertLess(n, m)
def test__cmp__const(self):
n = NUMBER(0, lineno=1)
m = CONST(NUMBER(1, lineno=2), lineno=2)
m2 = CONST(NUMBER(0, lineno=3), lineno=3)
self.assertNotEqual(n, m)
self.assertEqual(n, n)
self.assertNotEqual(n, 2)
self.assertEqual(n, 0)
self.assertGreater(n, -1)
self.assertLess(n, 1)
self.assertGreater(m, n)
self.assertLess(n, m)
self.assertEqual(n, m2)
self.assertEqual(m2, n)
def test__t(self):
n = NUMBER(3.14, 1)
self.assertEqual(n.t, '3.14')
def test__add__num_num(self):
a = NUMBER(1, 0)
b = NUMBER(2, 0)
self.assertEqual((a + b).t, '3')
def test__add__num_const(self):
a = NUMBER(1, 0)
b = CONST(NUMBER(2, 0), 0)
self.assertEqual((a + b).t, '3')
def test__add__num_value(self):
a = NUMBER(1, 0)
self.assertEqual((a + 2).t, '3')
def test__radd__num_const(self):
a = NUMBER(1, 0)
b = CONST(NUMBER(2, 0), 0)
self.assertEqual((b + a).t, '3')
def test__radd__num_value(self):
a = NUMBER(1, 0)
self.assertEqual((2 + a).t, '3')
def test__sub__num_num(self):
a = NUMBER(1, 0)
b = NUMBER(2, 0)
self.assertEqual((a - b).t, '-1')
def test__sub__num_const(self):
a = NUMBER(1, 0)
b = CONST(NUMBER(2, 0), 0)
self.assertEqual((a - b).t, '-1')
def test__sub__num_value(self):
a = NUMBER(1, 0)
self.assertEqual((a - 2).t, '-1')
def test__rsub__num_const(self):
a = NUMBER(2, 0)
b = CONST(NUMBER(1, 0), 0)
self.assertEqual((b - a).t, '-1')
def test__rsub__num_value(self):
a = NUMBER(2, 0)
self.assertEqual((1 - a).t, '-1')
def test__mul__num_num(self):
a = NUMBER(3, 0)
b = NUMBER(2, 0)
self.assertEqual((a * b).t, '6')
def test__mul__num_const(self):
a = NUMBER(3, 0)
b = CONST(NUMBER(2, 0), 0)
self.assertEqual((a * b).t, '6')
def test__mul__num_value(self):
a = NUMBER(3, 0)
self.assertEqual((a * 2).t, '6')
def test__rmul__num_const(self):
a = NUMBER(3, 0)
b = CONST(NUMBER(2, 0), 0)
self.assertEqual((b * a).t, '6')
def test__rmul__num_value(self):
a = NUMBER(3, 0)
self.assertEqual((2 * a).t, '6')
def test__div__num_num(self):
a = NUMBER(3, 0)
b = NUMBER(-2, 0)
self.assertEqual((a / b).t, str(a.value / b.value))
def test__div__num_const(self):
a = NUMBER(3, 0)
b = CONST(NUMBER(-2, 0), 0)
self.assertEqual((a / b).t, str(a.value / b.expr.value))
def test__div__num_value(self):
a = NUMBER(3, 0)
self.assertEqual((a / -2.0).t, '-1.5')
def test__rdiv__num_const(self):
a = CONST(NUMBER(-3, 0), 0)
b = NUMBER(2, 0)
self.assertEqual((a / b).t, str(a.expr.value / b.value))
def test__rdiv__num_value(self):
a = NUMBER(-2, 0)
self.assertEqual((3.0 / a).t, '-1.5')
def test__bor__val_num(self):
b = NUMBER(5, 0)
self.assertEqual((3 | b).t, '7')
def test__bor__num_val(self):
b = NUMBER(5, 0)
self.assertEqual((b | 3).t, '7')
def test__band__num_val(self):
b = NUMBER(5, 0)
self.assertEqual((b & 3).t, '1')
def test__band__val_num(self):
b = NUMBER(5, 0)
self.assertEqual((3 & b).t, '1')
def test__mod__num_val(self):
b = NUMBER(5, 0)
self.assertEqual((b % 3).t, '2')
def test__mod__val_num(self):
b = NUMBER(3, 0)
self.assertEqual((5 % b).t, '2')
def test__le__val_num(self):
b = NUMBER(3, 0)
self.assertLessEqual(2, b)
def test__le__num_num(self):
a = NUMBER(2, 0)
b = NUMBER(3, 0)
self.assertLessEqual(a, b)
def test__ge__val_num(self):
b = NUMBER(1, 0)
self.assertGreaterEqual(2, b)
def test__ge__num_num(self):
a = NUMBER(4, 0)
b = NUMBER(3, 0)
self.assertGreaterEqual(a, b)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolNUMBER.py
|
test_symbolNUMBER.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
from symbols.type_ import Type
class TestSymbolSTRING(TestCase):
def test__init__(self):
self.assertRaises(AssertionError, symbols.STRING, 0, 1)
_zxbasic = 'zxbasic'
_ZXBASIC = 'ZXBASIC'
s = symbols.STRING(_zxbasic, 1)
t = symbols.STRING(_ZXBASIC, 2)
self.assertEqual(s, s)
self.assertNotEqual(s, t)
self.assertEqual(s, _zxbasic)
self.assertEqual(_ZXBASIC, t)
self.assertGreater(s, t)
self.assertLess(t, s)
self.assertGreaterEqual(s, t)
self.assertLessEqual(t, s)
self.assertEqual(s.type_, Type.string)
self.assertEqual(str(s), _zxbasic)
self.assertEqual('"{}"'.format(_zxbasic), s.__repr__())
self.assertEqual(s.t, _zxbasic)
s.t = _ZXBASIC
self.assertEqual(s.t, _ZXBASIC)
self.assertRaises(AssertionError, symbols.STRING.t.fset, s, 0)
self.assertEqual(s.value, _zxbasic)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolSTRING.py
|
test_symbolSTRING.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from six import StringIO
from api.config import OPTIONS
import symbols
from libzxbpp import zxbpp
class TestSymbolBOUND(TestCase):
def setUp(self):
zxbpp.init()
def test__init__(self):
self.assertRaises(AssertionError, symbols.BOUND, 'a', 3)
self.assertRaises(AssertionError, symbols.BOUND, 1, 'a')
self.assertRaises(AssertionError, symbols.BOUND, 3, 1)
def test_count(self):
lower = 1
upper = 3
b = symbols.BOUND(lower, upper)
self.assertEqual(b.count, upper - lower + 1)
def test_make_node(self):
self.clearOutput()
l = symbols.NUMBER(2, lineno=1)
u = symbols.NUMBER(3, lineno=2)
symbols.BOUND.make_node(l, u, 3)
self.assertEqual(self.stderr, '')
l = symbols.NUMBER(4, lineno=1)
symbols.BOUND.make_node(l, u, 3)
self.assertEqual(self.stderr, '(stdin):3: error: Lower array bound must be less or equal to upper one\n')
self.clearOutput()
l = symbols.NUMBER(-4, lineno=1)
symbols.BOUND.make_node(l, u, 3)
self.assertEqual(self.stderr, '(stdin):3: error: Array bounds must be greater than 0\n')
self.clearOutput()
l = symbols.VAR('a', 10)
symbols.BOUND.make_node(l, u, 3)
self.assertEqual(self.stderr, '(stdin):3: error: Array bounds must be constants\n')
def test__str__(self):
b = symbols.BOUND(1, 3)
self.assertEqual(str(b), '(1 TO 3)')
def test__repr__(self):
b = symbols.BOUND(1, 3)
self.assertEqual(b.__repr__(), b.token + '(1 TO 3)')
def clearOutput(self):
OPTIONS.remove_option('stderr')
OPTIONS.add_option('stderr', default_value=StringIO())
@property
def stderr(self):
return OPTIONS.stderr.value.getvalue()
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolBOUND.py
|
test_symbolBOUND.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
import symbols
from api.constants import CLASS
class TestSymbolFUNCTION(TestCase):
def setUp(self):
self.fname = 'test'
self.f = symbols.FUNCTION(self.fname, 1)
def test__init__(self):
self.assertTrue(self.f.callable)
self.assertEqual(self.f.class_, CLASS.function)
self.assertEqual(self.fname, self.f.name)
self.assertEqual(self.f.mangled, '_%s' % self.f.name)
'''
def test_fromVAR(self):
f = symbols.FUNCTION.fromVAR(symbols.VAR(self.f.name, lineno=2))
self.assertEqual(f.name, self.f.name)
self.assertTrue(f.callable)
self.assertEqual(f.mangled, self.f.mangled)
self.assertEqual(f.class_, CLASS.function)
'''
def test_params_getter(self):
self.assertIsInstance(self.f.params, symbols.PARAMLIST)
self.assertEqual(len(self.f.params), 0)
def test_params_setter(self):
params = symbols.PARAMLIST()
self.f.params = params
self.assertEqual(self.f.params, params)
def test_body_getter(self):
self.assertIsInstance(self.f.body, symbols.BLOCK)
self.assertEqual(len(self.f.body), 0)
def test_body_setter(self):
body = symbols.BLOCK(symbols.NUMBER(0, lineno=1))
self.f.body = body
self.assertEqual(len(self.f.body), len(body))
self.assertEqual(self.f.body, body)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolFUNCTION.py
|
test_symbolFUNCTION.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from symbols import BLOCK
from symbols import NUMBER
__author__ = 'boriel'
class TestSymbolBLOCK(TestCase):
def test_make_node_empty(self):
BLOCK.make_node()
def test_make_node_empty2(self):
b = BLOCK.make_node(None, None)
self.assertEqual(b, BLOCK())
def test_make_node_simple(self):
b = BLOCK.make_node(NUMBER(1, lineno=1))
self.assertIsInstance(b, BLOCK)
def test__len__(self):
b = BLOCK.make_node(NUMBER(1, lineno=1))
self.assertEqual(len(b), 1)
def test__getitem__0(self):
n = NUMBER(1, lineno=1)
b = BLOCK.make_node(n)
self.assertEqual(b[0], n)
def test_getitem__error(self):
n = NUMBER(1, lineno=1)
b = BLOCK.make_node(n)
self.assertRaises(IndexError, b.__getitem__, len(b))
def test_make_node_wrong(self):
self.assertRaises(AssertionError, BLOCK.make_node, 1)
def test_make_node_optimize1(self):
b = BLOCK.make_node(BLOCK(NUMBER(1, lineno=1)))
self.assertIsInstance(b[0], NUMBER)
def test_make_node_optimize2(self):
n = NUMBER(1, lineno=1)
b = BLOCK.make_node(BLOCK(n), n, BLOCK(n))
self.assertEqual(len(b), 3)
for x in b:
self.assertIsInstance(x, NUMBER)
def test_make_node_optimize3(self):
n = NUMBER(1, lineno=1)
b = BLOCK.make_node(BLOCK(BLOCK(BLOCK())), BLOCK(BLOCK(n), BLOCK(BLOCK())))
self.assertEqual(len(b), 1)
self.assertEqual(b, BLOCK(n))
def test__eq__(self):
b = BLOCK()
self.assertEqual(b, b)
q = BLOCK()
self.assertEqual(b, q)
def test__eq__2(self):
n = NUMBER(1, lineno=1)
b = BLOCK.make_node(n)
self.assertEqual(b, b)
q = BLOCK()
self.assertNotEqual(b, q)
self.assertNotEqual(q, None)
self.assertNotEqual(None, q)
self.assertNotEqual(q, 'STRING')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolBLOCK.py
|
test_symbolBLOCK.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from symbols import NOP
__author__ = 'boriel'
class TestSymbolBLOCK(TestCase):
def setUp(self):
self.nop = NOP()
def test__len_0(self):
self.assertEqual(len(self.nop), 0, "NOP must have 0 length")
def test__assert_false(self):
self.assertFalse(self.nop)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolNOP.py
|
test_symbolNOP.py
|
# -*- coding: utf-8 -*-
__author__ = 'boriel'
from unittest import TestCase
from symbols import LABEL
class TestSymbolLABEL(TestCase):
def setUp(self):
self.label_name = 'test'
self.l = LABEL(self.label_name, 1)
def test_t(self):
self.assertEqual(self.l.t, LABEL.prefix + self.label_name)
def test_accessed(self):
self.assertFalse(self.l.accessed)
def test_scope_owner(self):
self.assertEqual(self.l.scope_owner, list())
def test_scope_owner_set(self):
tmp = LABEL('another', 2)
self.l.scope_owner = [tmp]
self.assertEqual(self.l.scope_owner, [tmp])
def test_set_accessed(self):
tmp = LABEL('another', 2)
self.l.scope_owner = [tmp]
self.l.accessed = True
self.assertTrue(self.l.accessed)
self.assertTrue(tmp.accessed)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolLABEL.py
|
test_symbolLABEL.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from api.constants import TYPE
from symbols.type_ import SymbolBASICTYPE
from symbols.type_ import SymbolTYPEALIAS
class TestSymbolTYPEALIAS(TestCase):
def test__eq__(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
ta = SymbolTYPEALIAS('alias', 0, t)
self.assertEqual(t.size, ta.size)
self.assertTrue(ta == ta)
self.assertTrue(t == ta)
self.assertTrue(ta == t)
def test_is_alias(self):
for type_ in TYPE.types:
t = SymbolBASICTYPE(type_)
ta = SymbolTYPEALIAS('alias', 0, t)
self.assertTrue(ta.is_alias)
self.assertTrue(ta.is_basic)
self.assertFalse(t.is_alias)
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/test_symbolTYPEALIAS.py
|
test_symbolTYPEALIAS.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
# Initialization
path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
sys.path.insert(0, path)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/symbols/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from six import StringIO
from api.symboltable import SymbolTable
from api.constants import TYPE
from api.constants import SCOPE
from api.constants import CLASS
from api.constants import DEPRECATED_SUFFIXES
from api.config import OPTIONS
import api.global_ as gl_
import symbols
class TestSymbolTable(TestCase):
def setUp(self):
self.clearOutput()
self.s = gl_.SYMBOL_TABLE = SymbolTable()
l1, l2, l3, l4 = 1, 2, 3, 4
b = symbols.BOUND(l1, l2)
c = symbols.BOUND(l3, l4)
self.bounds = symbols.BOUNDLIST.make_node(None, b, c)
self.func = symbols.FUNCDECL.make_node('testfunction', 1)
def test__init__(self):
""" Tests symbol table initialization
"""
OPTIONS.optimization.push()
OPTIONS.optimization.value = 0
self.assertEqual(len(self.s.types), len(TYPE.types))
for type_ in self.s.types:
self.assertTrue(type_.is_basic)
self.assertIsInstance(type_, symbols.BASICTYPE)
self.assertEqual(self.s.current_scope, self.s.global_scope)
OPTIONS.optimization.pop()
def test_is_declared(self):
# Checks variable 'a' is not declared yet
self.assertFalse(self.s.check_is_declared('a', 0, 'var', show_error=False))
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
# Checks variable 'a' is declared
self.assertTrue(self.s.check_is_declared('a', 1, 'var', show_error=False))
def test_is_undeclared(self):
s = SymbolTable()
# Checks variable 'a' is undeclared
self.assertTrue(s.check_is_undeclared('a', 10, show_error=False))
s.declare_variable('a', 10, self.btyperef(TYPE.integer))
# Checks variable 'a' is not undeclared
self.assertFalse(s.check_is_undeclared('a', 10, show_error=False))
def test_declare_variable(self):
# Declares 'a' (integer) variable
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
self.assertIsNotNone(self.s[self.s.current_scope]['a'])
def test_declare_variable_dupl(self):
# Declares 'a' (integer) variable
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
# Now checks for duplicated name 'a'
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
self.assertEqual(self.OUTPUT,
"(stdin):10: error: Variable 'a' already declared at (stdin):10\n")
def test_declare_variable_dupl_suffix(self):
# Declares 'a' (integer) variable
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
# Checks for duplicated var name using suffixes
self.s.declare_variable('a%', 11, self.btyperef(TYPE.integer))
self.assertEqual(self.OUTPUT,
"(stdin):11: error: Variable 'a%' already declared at (stdin):10\n")
def test_declare_variable_wrong_suffix(self):
self.s.declare_variable('b%', 12, self.btyperef(TYPE.byte_))
self.assertEqual(self.OUTPUT,
"(stdin):12: error: 'b%' suffix is for type 'integer' but it was declared as 'byte'\n")
def test_declare_variable_remove_suffix(self):
# Ensures suffix is removed
self.s.declare_variable('c%', 12, self.btyperef(TYPE.integer))
self.assertFalse(self.s.get_entry('c').name[-1] in DEPRECATED_SUFFIXES)
def test_declare_param_dupl(self):
# Declares 'a' (integer) variable
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
# Now declares 'a' (integer) parameter
p = self.s.declare_param('a', 11, self.btyperef(TYPE.integer))
self.assertIsNone(p)
self.assertEqual(self.OUTPUT, '(stdin):11: error: Duplicated parameter "a" (previous one at (stdin):10)\n')
def test_declare_param(self):
# Declares 'a' (integer) parameter
p = self.s.declare_param('a', 11, self.btyperef(TYPE.integer))
self.assertIsInstance(p, symbols.PARAMDECL)
self.assertEqual(p.scope, SCOPE.parameter)
self.assertEqual(p.class_, CLASS.var)
self.assertNotEqual(p.t[0], '$')
def test_declare_param_str(self):
# Declares 'a' (integer) parameter
p = self.s.declare_param('a', 11, self.btyperef(TYPE.string))
self.assertIsInstance(p, symbols.PARAMDECL)
self.assertEqual(p.scope, SCOPE.parameter)
self.assertEqual(p.class_, CLASS.var)
self.assertEqual(p.t[0], '$')
def test_get_entry(self):
s = SymbolTable()
var_a = s.get_entry('a')
self.assertIsNone(var_a)
s.declare_variable('a', 10, self.btyperef(TYPE.integer))
var_a = s.get_entry('a')
self.assertIsNotNone(var_a)
self.assertIsInstance(var_a, symbols.VAR)
self.assertEqual(var_a.scope, SCOPE.global_)
def test_enter_scope(self):
# Declares a variable named 'a'
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
self.s.enter_scope('testfunction')
self.assertNotEqual(self.s.current_scope, self.s.global_scope)
self.assertTrue(self.s.check_is_undeclared('a', 11, scope=self.s.current_scope))
def test_declare_local_var(self):
self.s.enter_scope('testfunction')
self.s.declare_variable('a', 12, self.btyperef(TYPE.float_))
self.assertTrue(self.s.check_is_declared('a', 11, scope=self.s.current_scope))
self.assertEqual(self.s.get_entry('a').scope, SCOPE.local)
def test_declare_array(self):
self.s.declare_array('test', lineno=1, type_=self.btyperef(TYPE.byte_), bounds=self.bounds)
def test_declare_array_fail(self):
# type_ must by an instance of symbols.TYPEREF
self.assertRaises(AssertionError, self.s.declare_array, 'test', 1, TYPE.byte_, self.bounds)
def test_declare_array_fail2(self):
# bounds must by an instance of symbols.BOUNDLIST
self.assertRaises(AssertionError, self.s.declare_array, 'test', 1, self.btyperef(TYPE.byte_),
'bla')
def test_declare_local_array(self):
""" the logic for declaring a local array differs from
local scalar variables
"""
self.s.enter_scope('testfunction')
self.s.declare_array('a', 12, self.btyperef(TYPE.float_),
symbols.BOUNDLIST(symbols.BOUND(0, 2)))
self.assertTrue(self.s.check_is_declared('a', 11, scope=self.s.current_scope))
self.assertEqual(self.s.get_entry('a').scope, SCOPE.local)
def test_declare_local_var_dup(self):
self.s.enter_scope('testfunction')
self.s.declare_variable('a', 12, self.btyperef(TYPE.float_))
# Now checks for duplicated name 'a'
self.s.declare_variable('a', 14, self.btyperef(TYPE.float_))
self.assertEqual(self.OUTPUT,
"(stdin):14: error: Variable 'a' already declared at (stdin):12\n")
def test_leave_scope(self):
self.s.enter_scope('testfunction')
# Declares a variable named 'a'
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
self.s.leave_scope()
self.assertEqual(self.s.current_scope, self.s.global_scope)
def test_local_var_cleaned(self):
self.s.enter_scope('testfunction')
# Declares a variable named 'a'
self.s.declare_variable('a', 10, self.btyperef(TYPE.integer))
self.s.leave_scope()
self.assertTrue(self.s.check_is_undeclared('a', 10))
def btyperef(self, type_):
assert TYPE.is_valid(type_)
return symbols.TYPEREF(symbols.BASICTYPE(type_), 0)
def clearOutput(self):
OPTIONS.remove_option('stderr')
OPTIONS.add_option('stderr', default_value=StringIO())
@property
def OUTPUT(self):
return OPTIONS.stderr.value.getvalue()
if __name__ == '__main__':
unittest.main()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/api/test_symbolTable.py
|
test_symbolTable.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from api import config
from api import global_
class TestConfig(unittest.TestCase):
""" Tests api.config initialization
"""
def setUp(self):
config.OPTIONS.reset()
def test_init(self):
config.init()
self.assertEqual(config.OPTIONS.Debug.value, 0)
self.assertEqual(config.OPTIONS.stdin.value, sys.stdin)
self.assertEqual(config.OPTIONS.stdout.value, sys.stdout)
self.assertEqual(config.OPTIONS.stderr.value, sys.stderr)
self.assertEqual(config.OPTIONS.optimization.value, global_.DEFAULT_OPTIMIZATION_LEVEL)
self.assertEqual(config.OPTIONS.case_insensitive.value, False)
self.assertEqual(config.OPTIONS.array_base.value, 0)
self.assertEqual(config.OPTIONS.byref.value, False)
self.assertEqual(config.OPTIONS.max_syntax_errors.value, global_.DEFAULT_MAX_SYNTAX_ERRORS)
self.assertEqual(config.OPTIONS.string_base.value, 0)
self.assertEqual(config.OPTIONS.memory_map.value, None)
self.assertEqual(config.OPTIONS.bracket.value, False)
self.assertEqual(config.OPTIONS.use_loader.value, False)
self.assertEqual(config.OPTIONS.autorun.value, False)
self.assertEqual(config.OPTIONS.output_file_type.value, 'bin')
self.assertEqual(config.OPTIONS.include_path.value, '')
self.assertEqual(config.OPTIONS.memoryCheck.value, False)
self.assertEqual(config.OPTIONS.strictBool.value, False)
self.assertEqual(config.OPTIONS.arrayCheck.value, False)
self.assertEqual(config.OPTIONS.enableBreak.value, False)
self.assertEqual(config.OPTIONS.emitBackend.value, False)
self.assertEqual(config.OPTIONS.arch.value, 'zx48k')
# private options that cannot be accessed with #pragma
self.assertEqual(config.OPTIONS.option('__DEFINES').value, {})
self.assertEqual(config.OPTIONS.explicit.value, False)
self.assertEqual(config.OPTIONS.Sinclair.value, False)
self.assertEqual(config.OPTIONS.strict.value, False)
def test_initted_values(self):
config.init()
self.assertEqual(sorted(config.OPTIONS.options.keys()), ['Debug',
'Sinclair',
'StdErrFileName',
'__DEFINES',
'arch',
'arrayCheck',
'array_base',
'autorun',
'bracket',
'byref',
'case_insensitive',
'emitBackend',
'enableBreak',
'explicit',
'include_path',
'inputFileName',
'max_syntax_errors',
'memoryCheck',
'memory_map',
'optimization',
'outputFileName',
'output_file_type',
'stderr',
'stdin',
'stdout',
'strict',
'strictBool',
'string_base',
'use_loader',
'zxnext'])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/api/test_config.py
|
test_config.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/api/__init__.py
|
__init__.py
|
# -*- coding: utf-8 -*-
import pytest
from libzxbc import zxb
import os
PATH = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
class EnsureRemoveFile(object):
""" Ensures a filename is removed if exists after
a block of code is executed
"""
def __init__(self, output_file_name):
self.fname = output_file_name
def remove_file(self):
if os.path.isfile(self.fname):
os.unlink(self.fname)
def __enter__(self):
self.remove_file()
def __exit__(self, exc_type, exc_val, exc_tb):
self.remove_file()
@pytest.fixture
def file_bas():
return os.path.join(PATH, 'empty.bas')
@pytest.fixture
def file_bin():
return os.path.join(PATH, 'empty.bin')
def test_compile_only(file_bas, file_bin):
""" Should not generate a file
"""
with EnsureRemoveFile(file_bin):
zxb.main(['--parse-only', file_bas, '-o', file_bin])
assert not os.path.isfile(file_bin), 'Should not create file "empty.bin"'
def test_org_allows_0xnnnn_format(file_bas, file_bin):
""" Should allow hexadecimal format 0x in org
"""
with EnsureRemoveFile(file_bin):
zxb.main(['--parse-only', '--org', '0xC000', file_bas, '-o', file_bin])
assert zxb.OPTIONS.org.value == 0xC000, 'Should set ORG to 0xC000'
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/cmdline/test_zxb.py
|
test_zxb.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
sys.path.insert(0, path)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/tests/cmdline/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
#
# This is the Parser for the ZXBASM (ZXBasic Assembler)
# ----------------------------------------------------------------------
import sys
import os
import argparse
from . import asmparse
from libzxbpp import zxbpp
import api.config
from api.config import OPTIONS
from api import global_
# Release version
VERSION = '1.13.1'
def main(args=None):
# Initializes asm parser state
api.config.init()
asmparse.init()
zxbpp.init()
# Create option parser
o_parser = argparse.ArgumentParser()
o_parser.add_argument('PROGRAM', type=str, help='ASM program file')
o_parser.add_argument("-d", "--debug", action="count", default=OPTIONS.Debug.value,
help="Enable verbosity/debugging output")
o_parser.add_argument("-O", "--optimize", type=int, dest="optimization_level",
help="Sets optimization level. 0 = None", default=OPTIONS.optimization.value)
o_parser.add_argument("-o", "--output", type=str, dest="output_file",
help="Sets output file. Default is input filename with .bin extension", default=None)
o_parser.add_argument("-T", "--tzx", action="store_true", dest="tzx", default=False,
help="Sets output format to tzx (default is .bin)")
o_parser.add_argument("-t", "--tap", action="store_true", dest="tap", default=False,
help="Sets output format to tzx (default is .bin)")
o_parser.add_argument("-B", "--BASIC", action="store_true", dest="basic", default=False,
help="Creates a BASIC loader which load the rest of the CODE. Requires -T ot -t")
o_parser.add_argument("-a", "--autorun", action="store_true", default=False,
help="Sets the program to auto run once loaded (implies --BASIC)")
o_parser.add_argument("-e", "--errmsg", type=str, dest="stderr", default=OPTIONS.StdErrFileName.value,
help="Error messages file (standard error console by default")
o_parser.add_argument("-M", "--mmap", type=str, dest="memory_map", default=None,
help="Generate label memory map")
o_parser.add_argument("-b", "--bracket", action="store_true", default=False,
help="Allows brackets only for memory access and indirections")
o_parser.add_argument('-N', "--zxnext", action="store_true", default=False,
help="Enable ZX Next extra ASM opcodes!")
o_parser.add_argument("--version", action="version", version="%(prog)s " + VERSION)
options = o_parser.parse_args(args)
if not os.path.exists(options.PROGRAM):
o_parser.error("No such file or directory: '%s'" % options.PROGRAM)
sys.exit(2)
OPTIONS.Debug.value = int(options.debug)
OPTIONS.inputFileName.value = options.PROGRAM
OPTIONS.outputFileName.value = options.output_file
OPTIONS.optimization.value = options.optimization_level
OPTIONS.use_loader.value = options.autorun or options.basic
OPTIONS.autorun.value = options.autorun
OPTIONS.StdErrFileName.value = options.stderr
OPTIONS.memory_map.value = options.memory_map
OPTIONS.bracket.value = options.bracket
OPTIONS.zxnext.value = options.zxnext
if options.tzx:
OPTIONS.output_file_type.value = 'tzx'
elif options.tap:
OPTIONS.output_file_type.value = 'tap'
if not OPTIONS.outputFileName.value:
OPTIONS.outputFileName.value = os.path.splitext(
os.path.basename(OPTIONS.inputFileName.value))[0] + os.path.extsep + OPTIONS.output_file_type.value
if OPTIONS.StdErrFileName.value:
OPTIONS.stderr.value = open(OPTIONS.StdErrFileName.value, 'wt')
if int(options.tzx) + int(options.tap) > 1:
o_parser.error("Options --tap, --tzx and --asm are mutually exclusive")
return 3
if OPTIONS.use_loader.value and not options.tzx and not options.tap:
o_parser.error('Option --BASIC and --autorun requires --tzx or tap format')
return 4
# Configure the preprocessor to use the asm-preprocessor-lexer
zxbpp.setMode('asm')
# Now filter them against the preprocessor
zxbpp.main([OPTIONS.inputFileName.value])
# Now output the result
asm_output = zxbpp.OUTPUT
asmparse.assemble(asm_output)
if global_.has_errors:
return 1
if not asmparse.MEMORY.memory_bytes: # empty seq.
asmparse.warning(0, "Nothing to assemble. Exiting...")
return 0
current_org = max(asmparse.MEMORY.memory_bytes.keys() or [0]) + 1
for label, line in asmparse.INITS:
expr_label = asmparse.Expr.makenode(asmparse.Container(asmparse.MEMORY.get_label(label, line), line))
asmparse.MEMORY.add_instruction(asmparse.Asm(0, 'CALL NN', expr_label))
if len(asmparse.INITS) > 0:
if asmparse.AUTORUN_ADDR is not None:
asmparse.MEMORY.add_instruction(asmparse.Asm(0, 'JP NN', asmparse.AUTORUN_ADDR))
else:
asmparse.MEMORY.add_instruction(
asmparse.Asm(0, 'JP NN', min(asmparse.MEMORY.orgs.keys()))) # To the beginning of binary
asmparse.AUTORUN_ADDR = current_org
if OPTIONS.memory_map.value:
with open(OPTIONS.memory_map.value, 'wt') as f:
f.write(asmparse.MEMORY.memory_map)
asmparse.generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type.value)
return global_.has_errors
if __name__ == '__main__':
sys.exit(main())
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/zxbasm.py
|
zxbasm.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:ts=4:et:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
#
# This is the Lexer for the ZXBpp (ZXBasic Preprocessor)
# ----------------------------------------------------------------------
import ply.lex as lex
import sys
from api.config import OPTIONS
from api.errmsg import error
_tokens = ('STRING', 'NEWLINE', 'CO',
'ID', 'COMMA', 'PLUS', 'MINUS', 'LP', 'RP', 'LPP', 'RPP', 'MUL', 'DIV', 'POW', 'MOD',
'UMINUS', 'APO', 'INTEGER', 'ADDR',
'LSHIFT', 'RSHIFT', 'BAND', 'BOR', 'BXOR'
)
reserved_instructions = {
'adc': 'ADC',
'add': 'ADD',
'and': 'AND',
'bit': 'BIT',
'call': 'CALL',
'ccf': 'CCF',
'cp': 'CP',
'cpd': 'CPD',
'cpdr': 'CPDR',
'cpi': 'CPI',
'cpir': 'CPIR',
'cpl': 'CPL',
'daa': 'DAA',
'dec': 'DEC',
'di': 'DI',
'djnz': 'DJNZ',
'ei': 'EI',
'ex': 'EX',
'exx': 'EXX',
'halt': 'HALT',
'im': 'IM',
'in': 'IN',
'inc': 'INC',
'ind': 'IND',
'indr': 'INDR',
'ini': 'INI',
'inir': 'INIR',
'jp': 'JP',
'jr': 'JR',
'ld': 'LD',
'ldd': 'LDD',
'lddr': 'LDDR',
'ldi': 'LDI',
'ldir': 'LDIR',
'neg': 'NEG',
'nop': 'NOP',
'or': 'OR',
'otdr': 'OTDR',
'otir': 'OTIR',
'out': 'OUT',
'outd': 'OUTD',
'outi': 'OUTI',
'pop': 'POP',
'push': 'PUSH',
'res': 'RES',
'ret': 'RET',
'reti': 'RETI',
'retn': 'RETN',
'rl': 'RL',
'rla': 'RLA',
'rlc': 'RLC',
'rlca': 'RLCA',
'rld': 'RLD',
'rr': 'RR',
'rra': 'RRA',
'rrc': 'RRC',
'rrca': 'RRCA',
'rrd': 'RRD',
'rst': 'RST',
'sbc': 'SBC',
'scf': 'SCF',
'set': 'SET',
'sla': 'SLA',
'sll': 'SLL',
'sra': 'SRA',
'srl': 'SRL',
'sub': 'SUB',
'xor': 'XOR',
}
zx_next_mnemonics = {
x.lower(): x for x in [
"LDIX",
"LDWS",
"LDIRX",
"LDDX",
"LDDRX",
"LDPIRX",
"OUTINB",
"MUL",
"SWAPNIB",
"MIRROR",
"NEXTREG",
"PIXELDN",
"PIXELAD",
"SETAE",
"TEST",
"BSLA",
"BSRA",
"BSRL",
"BSRF",
"BRLC"
]
}
pseudo = { # pseudo ops
'align': 'ALIGN',
'org': 'ORG',
'defb': 'DEFB',
'defm': 'DEFB',
'db': 'DEFB',
'defs': 'DEFS',
'defw': 'DEFW',
'ds': 'DEFS',
'dw': 'DEFW',
'equ': 'EQU',
'proc': 'PROC',
'endp': 'ENDP',
'local': 'LOCAL',
'end': 'END',
'incbin': 'INCBIN',
'namespace': 'NAMESPACE'
}
regs8 = {'a': 'A',
'b': 'B', 'c': 'C',
'd': 'D', 'e': 'E',
'h': 'H', 'l': 'L',
'i': 'I', 'r': 'R',
'ixh': 'IXH', 'ixl': 'IXL',
'iyh': 'IYH', 'iyl': 'IYL'
}
regs16 = {
'af': 'AF',
'bc': 'BC',
'de': 'DE',
'hl': 'HL',
'ix': 'IX',
'iy': 'IY',
'sp': 'SP'
}
flags = {
'z': 'Z',
'nz': 'NZ',
'nc': 'NC',
'po': 'PO',
'pe': 'PE',
'p': 'P',
'm': 'M',
}
preprocessor = {
'init': '_INIT',
'line': '_LINE'
}
# List of token names.
_tokens = sorted(
_tokens +
tuple(reserved_instructions.values()) +
tuple(pseudo.values()) +
tuple(regs8.values()) +
tuple(regs16.values()) +
tuple(flags.values()) +
tuple(zx_next_mnemonics.values()) +
tuple(preprocessor.values())
)
keywords = set(
flags.keys()).union(
regs16.keys()).union(
regs8.keys()).union(
pseudo.keys()).union(
reserved_instructions.keys()).union(
zx_next_mnemonics.keys())
def get_uniques(l):
""" Returns a list with no repeated elements.
"""
result = []
for i in l:
if i not in result:
result.append(i)
return result
tokens = get_uniques(_tokens)
class Lexer(object):
""" Own class lexer to allow multiple instances.
This lexer is just a wrapper of the current FILESTACK[-1] lexer
"""
states = (
('preproc', 'exclusive'),
)
# -------------- TOKEN ACTIONS --------------
def __set_lineno(self, value):
""" Setter for lexer.lineno
"""
self.lex.lineno = value
def __get_lineno(self):
""" Getter for lexer.lineno
"""
if self.lex is None:
return 0
return self.lex.lineno
lineno = property(__get_lineno, __set_lineno)
def t_INITIAL_preproc_skip(self, t):
r'[ \t]+'
pass # Ignore whitespaces and tabs
def t_CHAR(self, t):
r"'.'" # A single char
t.value = ord(t.value[1])
t.type = 'INTEGER'
return t
def t_HEXA(self, t):
r'([0-9][0-9a-fA-F]*[hH])|(\$[0-9a-fA-F]+)|(0x[0-9a-fA-F]+)'
if t.value[:2] == '0x':
t.value = t.value[2:] # Remove initial 0x
elif t.value[0] == '$':
t.value = t.value[1:] # Remove initial '$'
else:
t.value = t.value[:-1] # Remove last 'h'
t.value = int(t.value, 16) # Convert to decimal
t.type = 'INTEGER'
return t
def t_BIN(self, t):
r'(%[01]+)|([01]+[bB])' # A Binary integer
# Note 00B is a 0 binary, but
# 00Bh is a 12 in hex. So this pattern must come
# after HEXA
if t.value[0] == '%':
t.value = t.value[1:] # Remove initial %
else:
t.value = t.value[:-1] # Remove last 'b'
t.value = int(t.value, 2) # Convert to decimal
t.type = 'INTEGER'
return t
def t_INITIAL_preproc_INTEGER(self, t):
r'[0-9]+' # an integer decimal number
t.value = int(t.value)
return t
def t_INITIAL_ID(self, t):
r'[._a-zA-Z][._a-zA-Z0-9]*' # Any identifier
tmp = t.value # Saves original value
t.value = tmp.upper() # Convert it to uppercase, since our internal tables uses uppercase
id_ = tmp.lower()
t.type = reserved_instructions.get(id_)
if t.type is not None:
return t
t.type = pseudo.get(id_)
if t.type is not None:
return t
t.type = regs8.get(id_)
if t.type is not None:
return t
t.type = flags.get(id_)
if t.type is not None:
return t
if OPTIONS.zxnext.value:
t.type = zx_next_mnemonics.get(id_)
if t.type is not None:
return t
t.type = regs16.get(id_, 'ID')
if t.type == 'ID':
t.value = tmp # Restores original value
return t
def t_preproc_ID(self, t):
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = preprocessor.get(t.value.lower(), 'ID')
return t
def t_COMMA(self, t):
r','
return t
def t_ADDR(self, t):
r'\$'
return t
def t_LP(self, t):
r'[\[(]'
if t.value != '[' and OPTIONS.bracket.value:
t.type = 'LPP'
return t
def t_RP(self, t):
r'[])]'
if t.value != ']' and OPTIONS.bracket.value:
t.type = 'RPP'
return t
def t_LSHIFT(self, t):
r'<<'
return t
def t_RSHIFT(self, t):
r'>>'
return t
def t_BAND(self, t):
r'&'
return t
def t_BOR(self, t):
r'\|'
return t
def t_BXOR(self, t):
r'~'
return t
def t_PLUS(self, t):
r'\+'
return t
def t_MINUS(self, t):
r'\-'
return t
def t_MUL(self, t):
r'\*'
return t
def t_DIV(self, t):
r'\/'
return t
def t_MOD(self, t):
r'\%'
return t
def t_POW(self, t):
r'\^'
return t
def t_APO(self, t):
r"'"
return t
def t_CO(self, t):
r":"
return t
def t_INITIAL_preproc_STRING(self, t):
r'"(""|[^"])*"' # a doubled quoted string
t.value = t.value[1:-1].replace('""', '"') # Remove quotes
return t
def t_INITIAL_preproc_CONTINUE(self, t):
r'\\\r?\n'
t.lexer.lineno += 1
# Allows line breaking
def t_COMMENT(self, t):
r';.*'
# Skip to end of line (except end of line)
def t_INITIAL_preproc_NEWLINE(self, t):
r'\r?\n'
t.lexer.lineno += 1
t.lexer.begin('INITIAL')
return t
def t_INITIAL_SHARP(self, t):
r'\#'
if self.find_column(t) == 1:
t.lexer.begin('preproc')
else:
self.t_INITIAL_preproc_error(t)
def t_INITIAL_preproc_ERROR(self, t):
r'.'
self.t_INITIAL_preproc_error(t)
def t_INITIAL_preproc_error(self, t):
# error handling rule
error(t.lexer.lineno, "illegal character '%s'" % t.value[0])
def __init__(self):
""" Creates a new GLOBAL lexer instance
"""
self.lex = None
self.filestack = [] # Current filename, and line number being parsed
self.input_data = ''
self.tokens = tokens
self.next_token = None # if set to something, this will be returned once
def input(self, str):
""" Defines input string, removing current lexer.
"""
self.input_data = str
self.lex = lex.lex(object=self)
self.lex.input(self.input_data)
def token(self):
return self.lex.token()
def find_column(self, token):
""" Compute column:
- token is a token instance
"""
i = token.lexpos
while i > 0:
if self.input_data[i - 1] == '\n':
break
i -= 1
column = token.lexpos - i + 1
return column
# --------------------- PREPROCESSOR FUNCTIONS -------------------
# Needed for states
tmp = lex.lex(object=Lexer())
if __name__ == '__main__':
tmp.input(open(sys.argv[1]).read())
tok = tmp.token()
while tok:
print(tok)
tok = tmp.token()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/asmlex.py
|
asmlex.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:et:sw=4
from libzxbasm.z80 import Opcode, Z80SET
from api.errors import Error
import re
# Reg. Exp. for counting N args in an asm mnemonic
ARGre = re.compile(r'\bN+\b')
Z80_re = {} # Reg. Expr dictionary to cache them
Z80_8REGS = ('A', 'B', 'C', 'D', 'E', 'H', 'L',
'IXh', 'IYh', 'IXl', 'IYl', 'I', 'R')
Z80_16REGS = {'AF': ('A', 'F'), 'BC': ('B', 'C'), 'DE': ('D', 'E'),
'HL': ('H', 'L'), 'SP': (),
'IX': ('IXh', 'IXl'), 'IY': ('IYh', 'IYl')
}
def num2bytes(x, bytes):
""" Returns x converted to a little-endian t-uple of bytes.
E.g. num2bytes(255, 4) = (255, 0, 0, 0)
"""
if not isinstance(x, int): # If it is another "thing", just return ZEROs
return tuple([0] * bytes)
x = x & ((2 << (bytes * 8)) - 1) # mask the initial value
result = ()
for i in range(bytes):
result += (x & 0xFF,)
x >>= 8
return result
class InvalidMnemonicError(Error):
""" Exception raised when an invalid Mnemonic has been emitted.
"""
def __init__(self, mnemo):
self.msg = "Invalid mnemonic '%s'" % mnemo
self.mnemo = mnemo
class InvalidArgError(Error):
""" Exception raised when an invalid argument has been emitted.
"""
def __init__(self, arg):
self.msg = "Invalid argument '%s'. It must be an integer." % str(arg)
self.mnemo = arg
class InternalMismatchSizeError(Error):
""" Exception raised when an invalid instruction length has been emitted.
"""
def __init__(self, current_size, asm):
a = '' if current_size == 1 else 's'
b = '' if asm.size == 1 else 's'
self.msg = ("Invalid instruction [%s] size (%i byte%s). "
"It should be %i byte%s." % (asm.asm, current_size, a,
asm.size, b))
self.current_size = current_size
self.asm = asm
class AsmInstruction(Opcode):
""" Derives from Opcode. This one checks for opcode validity.
"""
def __init__(self, asm, arg=None):
""" Parses the given asm instruction and validates
it against the Z80SET table. Raises InvalidMnemonicError
if not valid.
It uses the Z80SET global dictionary. Args is an optional
argument (it can be a Label object or a value)
"""
if isinstance(arg, list):
arg = tuple(arg)
if arg is None:
arg = ()
if arg is not None and not isinstance(arg, tuple):
arg = (arg,)
asm = asm.split(';', 1) # Try to get comments out, if any
if len(asm) > 1:
self.comments = ';' + asm[1]
else:
self.comments = ''
asm = asm[0]
if asm.upper() not in Z80SET.keys():
raise InvalidMnemonicError(asm)
self.mnemo = asm.upper()
Z80 = Z80SET[self.mnemo]
self.asm = asm
self.size = Z80.size
self.T = Z80.T
self.opcode = Z80.opcode
self.argbytes = tuple([len(x) for x in ARGre.findall(asm)])
self.arg = arg
self.arg_num = len(ARGre.findall(asm))
def argval(self):
""" Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered.
"""
if self.arg is None or any(x is None for x in self.arg):
return None
for x in self.arg:
if not isinstance(x, int):
raise InvalidArgError(self.arg)
return self.arg
def bytes(self):
""" Returns a t-uple with instruction bytes (integers)
"""
result = []
op = self.opcode.split(' ')
argi = 0
while op:
q = op.pop(0)
if q == 'XX':
for k in range(self.argbytes[argi] - 1):
op.pop(0)
result.extend(num2bytes(self.argval()[argi], self.argbytes[argi]))
argi += 1
else:
result.append(int(q, 16)) # Add opcode
if len(result) != self.size:
raise InternalMismatchSizeError(len(result), self)
return result
def __str__(self):
return self.asm
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/asm.py
|
asm.py
|
# -*- coding: utf-8 -*-
__all__ = [
'p_mul_d_e',
'p_simple_instruction',
'p_add_reg16_a',
'p_JP_c',
'p_bxxxx_de_b',
'p_add_reg_NN',
'p_test_nn',
'p_nextreg_expr',
'p_nextreg_a',
'p_push_imm'
]
from libzxbasm import asmparse
def p_mul_d_e(p):
""" asm : MUL D COMMA E
"""
p[0] = asmparse.Asm(p.lineno(1), 'MUL D,E')
def p_simple_instruction(p):
""" asm : LDIX
| LDWS
| LDIRX
| LDDX
| LDDRX
| LDPIRX
| OUTINB
| SWAPNIB
| MIRROR
| PIXELDN
| PIXELAD
| SETAE
"""
p[0] = asmparse.Asm(p.lineno(1), p[1])
def p_add_reg16_a(p):
""" asm : ADD HL COMMA A
| ADD DE COMMA A
| ADD BC COMMA A
"""
p[0] = asmparse.Asm(p.lineno(1), 'ADD {},A'.format(p[2]))
def p_JP_c(p):
""" asm : JP LP C RP
"""
p[0] = asmparse.Asm(p.lineno(1), 'JP (C)')
def p_bxxxx_de_b(p):
""" asm : BSLA DE COMMA B
| BSRA DE COMMA B
| BSRL DE COMMA B
| BSRF DE COMMA B
| BRLC DE COMMA B
"""
p[0] = asmparse.Asm(p.lineno(1), '{} DE,B'.format(p[1]))
def p_add_reg_NN(p):
""" asm : ADD HL COMMA expr
| ADD DE COMMA expr
| ADD BC COMMA expr
| ADD HL COMMA pexpr
| ADD DE COMMA pexpr
| ADD BC COMMA pexpr
"""
p[0] = asmparse.Asm(p.lineno(1), 'ADD {},NN'.format(p[2]), p[4])
def p_test_nn(p):
""" asm : TEST expr
| TEST pexpr
"""
p[0] = asmparse.Asm(p.lineno(1), 'TEST N', p[2])
def p_nextreg_expr(p):
""" asm : NEXTREG expr COMMA expr
| NEXTREG expr COMMA pexpr
| NEXTREG pexpr COMMA expr
| NEXTREG pexpr COMMA pexpr
"""
p[0] = asmparse.Asm(p.lineno(1), 'NEXTREG N,N', (p[2], p[4]))
def p_nextreg_a(p):
""" asm : NEXTREG expr COMMA A
| NEXTREG pexpr COMMA A
"""
p[0] = asmparse.Asm(p.lineno(1), 'NEXTREG N,A', p[2])
def p_push_imm(p):
""" asm : PUSH expr
| PUSH pexpr
"""
# Reverse HI | LO => X1 = (X0 & 0xFF) << 8 | (X0 >> 8) & 0xFF
mknod = asmparse.Expr.makenode
cont = lambda x: asmparse.Container(x, p.lineno(1))
ff = mknod(cont(0xFF))
n8 = mknod(cont(8))
expr = mknod(
cont('|'),
mknod(cont('<<'), mknod(cont('&'), p[2], ff), n8),
mknod(cont('&'), mknod(cont('>>'), p[2], n8), ff)
)
p[0] = asmparse.Asm(p.lineno(1), 'PUSH NN', expr)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/zxnext.py
|
zxnext.py
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Copyleft (K) 2008 by Jose M. Rodriguez de la Rosa
#
# Simple ASCII to BASIC tokenizer
#
# Implements a simple (really simple) ZX Spectrum BASIC tokenizer
# This will convert a simple ASCII text to a ZX spectrum BASIC bytes program
# -------------------------------------------------------------------------------
from api import fp
import outfmt.tzx as tzx
ENTER = 0x0D
TOKENS = {
'LOAD': 239,
'POKE': 244,
'PRINT': 245,
'RUN': 247,
'PEEK': 190,
'USR': 192,
'LINE': 202,
'CODE': 175,
'AT': 172,
'RANDOMIZE': 249,
'CLS': 251,
'CLEAR': 253,
'PAUSE': 242,
'LET': 241,
'INPUT': 238,
'READ': 227,
'DATA': 228,
'RESTORE': 229,
'NEW': 230,
'OUT': 223,
'BEEP': 215,
'INK': 217,
'PAPER': 218,
'BORDER': 231,
'REM': 234,
'FOR': 235,
'TO': 204,
'NEXT': 243,
'RETURN': 254,
'GOTO': 236,
'GO SUB': 237,
}
class Basic(object):
""" Class for a simple BASIC tokenizer
"""
def __init__(self):
self.bytes = [] # Array of bytes containing a ZX Spectrum BASIC program
self.current_line = 0 # Current basic_line
def line_number(self, number):
""" Returns the bytes for a line number.
This is BIG ENDIAN for the ZX Basic
"""
numberH = (number & 0xFF00) >> 8
numberL = number & 0xFF
return [numberH, numberL]
def numberLH(self, number):
""" Returns the bytes for 16 bits number.
This is LITTLE ENDIAN for the ZX Basic
"""
numberH = (number & 0xFF00) >> 8
numberL = number & 0xFF
return [numberL, numberH]
def number(self, number):
""" Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535)
"""
s = [ord(x) for x in str(number)] + [14] # Bytes of string representation in bytes
if number == int(number) and abs(number) < 65536: # integer form?
sign = 0xFF if number < 0 else 0
b = [0, sign] + self.numberLH(number) + [0]
else: # Float form
(C, ED, LH) = fp.immediate_float(number)
C = C[:2] # Remove 'h'
ED = ED[:4] # Remove 'h'
LH = LH[:4] # Remove 'h'
b = [int(C, 16)] # Convert to BASE 10
b += [int(ED[:2], 16), int(ED[2:], 16)]
b += [int(LH[:2], 16), int(LH[2:], 16)]
return s + b
def token(self, string):
""" Return the token for the given word
"""
string = string.upper()
return [TOKENS[string]]
def literal(self, string):
""" Return the current string "as is"
in bytes
"""
return [ord(x) for x in string]
def parse_sentence(self, string):
""" Parses the given sentence. BASIC commands must be
types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc...
"""
result = []
def shift(string_):
""" Returns first word of a string, and remaining
"""
string_ = string_.strip() # Remove spaces and tabs
if not string_: # Avoid empty strings
return '', ''
i = string_.find(' ')
if i == -1:
command_ = string_
string_ = ''
else:
command_ = string_[:i]
string_ = string_[i:]
return command_, string_
command, string = shift(string)
while command != '':
result += self.token(command)
def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
if isinstance(i, str):
result.extend(self.literal(i))
elif isinstance(i, float) or isinstance(i, int): # A number?
result.extend(self.number(i))
else:
result.extend(i) # Must be another thing
return result
def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10
self.current_line = line_number
sep = []
result = []
for sentence in sentences:
result.extend(sep)
result.extend(self.sentence_bytes(sentence))
sep = [ord(':')]
result.extend([ENTER])
result = self.line_number(line_number) + self.numberLH(len(result)) + result
return result
def add_line(self, sentences, line_number=None):
""" Add current line to the output.
See self.line() for more info
"""
self.bytes += self.line(sentences, line_number)
if __name__ == '__main__':
# Only as a test if invoked from command line
a = Basic()
a.add_line([['CLEAR', 31999]])
a.add_line([['POKE', 23610, ',', 255]])
a.add_line([['LOAD', '""', a.token('CODE')]])
a.add_line([['RANDOMIZE', a.token('USR'), 32000]])
t = tzx.TZX()
t.save_program('test.tzx', a.bytes, line=1)
t.dump('tzxtest.tzx')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/basic.py
|
basic.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: et:ts=4:sw=4:
# ----------------------------------------------------------------------
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
#
# This program is Free Software and is released under the terms of
# the GNU General License
#
# This is the Parser for the ZXBASM (ZXBasic Assembler)
# ----------------------------------------------------------------------
import os
import re
from . import asmlex, basic
import ply.yacc as yacc
from .asmlex import tokens # noqa
from .asm import AsmInstruction, Error
from ast_ import Ast
from ast_.tree import NotAnAstError
from api.debug import __DEBUG__
from api.config import OPTIONS
from api.errmsg import error as error
from api.errmsg import warning
from api import global_ as gl
import api.utils
from libzxbpp import zxbpp
import outfmt
LEXER = asmlex.Lexer()
ORG = 0 # Origin of CODE
INITS = []
MEMORY = None # Memory for instructions (Will be initialized with a Memory() instance)
AUTORUN_ADDR = None # Where to start the execution automatically
RE_DOTS = re.compile(r'\.+')
REGS16 = {'BC', 'DE', 'HL', 'SP', 'IX', 'IY'} # 16 Bits registers
precedence = (
('left', 'RSHIFT', 'LSHIFT', 'BAND', 'BOR', 'BXOR'),
('left', 'PLUS', 'MINUS'),
('left', 'MUL', 'DIV', 'MOD'),
('right', 'POW'),
('right', 'UMINUS'),
)
MAX_MEM = 65535 # Max memory limit
DOT = '.' # NAMESPACE separator
GLOBAL_NAMESPACE = DOT
NAMESPACE = GLOBAL_NAMESPACE # Current namespace (defaults to ''). It's a prefix added to each global label
def normalize_namespace(namespace):
""" Given a namespace (e.g. '.' or 'mynamespace'),
returns it in normalized form. That is:
- always prefixed with a dot
- no trailing dots
- any double dots are converted to single dot (..my..namespace => .my.namespace)
- one or more dots (e.g. '.', '..', '...') are converted to '.' (Global namespace)
"""
namespace = (DOT + DOT.join(RE_DOTS.split(namespace))).rstrip(DOT) + DOT
return namespace
def init():
""" Initializes this module
"""
global ORG
global LEXER
global MEMORY
global INITS
global AUTORUN_ADDR
global NAMESPACE
ORG = 0 # Origin of CODE
INITS = []
MEMORY = None # Memory for instructions (Will be initialized with a Memory() instance)
AUTORUN_ADDR = None # Where to start the execution automatically
NAMESPACE = GLOBAL_NAMESPACE # Current namespace (defaults to ''). It's a prefix added to each global label
gl.has_errors = 0
gl.error_msg_cache.clear()
class Asm(AsmInstruction):
""" Class extension to AsmInstruction with a short name :-P
and will trap some exceptions and convert them to error msgs.
It will also record source line
"""
def __init__(self, lineno, asm, arg=None):
self.lineno = lineno
if asm not in ('DEFB', 'DEFS', 'DEFW'):
try:
super(Asm, self).__init__(asm, arg)
except Error as v:
error(lineno, v.msg)
return
self.pending = len([x for x in self.arg if isinstance(x, Expr) and x.try_eval() is None]) > 0
if not self.pending:
self.arg = self.argval()
else:
self.asm = asm
self.pending = True
if isinstance(arg, str):
self.arg = tuple([Expr(Container(ord(x), lineno)) for x in arg])
else:
self.arg = arg
self.arg_num = len(self.arg)
def bytes(self):
""" Returns opcodes
"""
if self.asm not in ('DEFB', 'DEFS', 'DEFW'):
if self.pending:
tmp = self.arg # Saves current arg temporarily
self.arg = tuple([0] * self.arg_num)
result = super(Asm, self).bytes()
self.arg = tmp # And recovers it
return result
return super(Asm, self).bytes()
if self.asm == 'DEFB':
if self.pending:
return tuple([0] * self.arg_num)
return tuple(x & 0xFF for x in self.argval())
if self.asm == 'DEFS':
if self.pending:
N = self.arg[0]
if isinstance(N, Expr):
N = N.eval()
return tuple([0] * N) # ??
args = self.argval()
num = args[1] & 0xFF
return tuple([num] * args[0])
if self.pending: # DEFW
return tuple([0] * 2 * self.arg_num)
result = ()
for i in self.argval():
x = i & 0xFFFF
result += (x & 0xFF, x >> 8)
return result
def argval(self):
""" Solve args values or raise errors if not
defined yet
"""
if gl.has_errors:
return [None]
if self.asm in ('DEFB', 'DEFS', 'DEFW'):
return tuple([x.eval() if isinstance(x, Expr) else x for x in self.arg])
self.arg = tuple([x if not isinstance(x, Expr) else x.eval() for x in self.arg])
if gl.has_errors:
return [None]
if self.asm.split(' ')[0] in ('JR', 'DJNZ'): # A relative jump?
if self.arg[0] < -128 or self.arg[0] > 127:
error(self.lineno, 'Relative jump out of range')
return [None]
return super(Asm, self).argval()
class Container(object):
""" Single class container
"""
def __init__(self, item, lineno):
""" Item to store
"""
self.item = item
self.lineno = lineno
class Expr(Ast):
""" A class derived from AST that will
recursively parse its nodes and return the value
"""
ignore = True # Class flag
funct = {
'-': lambda x, y: x - y,
'+': lambda x, y: x + y,
'*': lambda x, y: x * y,
'/': lambda x, y: x // y,
'^': lambda x, y: x ** y,
'%': lambda x, y: x % y,
'&': lambda x, y: x & y,
'|': lambda x, y: x | y,
'~': lambda x, y: x ^ y,
'<<': lambda x, y: x << y,
'>>': lambda x, y: x >> y
}
def __init__(self, symbol=None):
""" Initializes ancestor attributes, and
ignore flags.
"""
Ast.__init__(self)
self.symbol = symbol
@property
def left(self):
if self.children:
return self.children[0]
@left.setter
def left(self, value):
if self.children:
self.children[0] = value
else:
self.children.append(value)
@property
def right(self):
if len(self.children) > 1:
return self.children[1]
@right.setter
def right(self, value):
if len(self.children) > 1:
self.children[1] = value
elif self.children:
self.children.append(value)
else:
self.children = [None, value]
def eval(self):
""" Recursively evals the node. Exits with an
error if not resolved.
"""
Expr.ignore = False
result = self.try_eval()
Expr.ignore = True
return result
def try_eval(self):
""" Recursively evals the node. Returns None
if it is still unresolved.
"""
item = self.symbol.item
if isinstance(item, int):
return item
if isinstance(item, Label):
if item.defined:
if isinstance(item.value, Expr):
return item.value.try_eval()
else:
return item.value
else:
if Expr.ignore:
return None
# Try to resolve into the global namespace
error(self.symbol.lineno, "Undefined label '%s'" % item.name)
return None
try:
if isinstance(item, tuple):
return tuple([x.try_eval() for x in item])
if isinstance(item, list):
return [x.try_eval() for x in item]
if item == '-' and len(self.children) == 1:
return -self.left.try_eval()
if item == '+' and len(self.children) == 1:
return self.left.try_eval()
try:
return self.funct[item](self.left.try_eval(), self.right.try_eval())
except ZeroDivisionError:
error(self.symbol.lineno, 'Division by 0')
except KeyError:
pass
except TypeError:
pass
return None
@classmethod
def makenode(cls, symbol, *nexts):
""" Stores the symbol in an AST instance,
and left and right to the given ones
"""
result = cls(symbol)
for i in nexts:
if i is None:
continue
if not isinstance(i, cls):
raise NotAnAstError(i)
result.appendChild(i)
return result
class Label(object):
""" A class to store Label information (NAME, linenumber and Address)
"""
def __init__(self, name, lineno, value=None, local=False, namespace=None, is_address=False):
""" Defines a Label object:
- name : The label name. e.g. __LOOP
- lineno : Where was this label defined.
- address : Memory address or numeric value this label refers
to (None if undefined yet)
- local : whether this is a local label or a global one
- namespace: If the label is DECLARED (not accessed), this is
its prefixed namespace
- is_address: Whether this label refers to a memory address (declared without EQU)
"""
self._name = name
self.lineno = lineno
self.value = value
self.local = local
self.namespace = namespace
self.current_namespace = NAMESPACE # Namespace under which the label was referenced (not declared)
self.is_address = is_address
@property
def defined(self):
""" Returns whether it has a value already or not.
"""
return self.value is not None
def define(self, value, lineno, namespace=None):
""" Defines label value. It can be anything. Even an AST
"""
if self.defined:
error(lineno, "label '%s' already defined at line %i" % (self.name, self.lineno))
self.value = value
self.lineno = lineno
self.namespace = NAMESPACE if namespace is None else namespace
def resolve(self, lineno):
""" Evaluates label value. Exits with error (unresolved) if value is none
"""
if not self.defined:
error(lineno, "Undeclared label '%s'" % self.name)
if isinstance(self.value, Expr):
return self.value.eval()
return self.value
@property
def name(self):
return self._name
class Memory(object):
""" A class to describe memory
"""
def __init__(self, org=0):
""" Initializes the origin of code.
0 by default """
self.index = org # ORG address (can be changed on the fly)
self.memory_bytes = {} # An array (associative) containing memory bytes
self.local_labels = [{}] # Local labels in the current memory scope
self.global_labels = self.local_labels[0] # Global memory labels
self.orgs = {} # Origins of code for asm mnemonics. This will store corresponding asm instructions
self.ORG = org # last ORG value set
self.scopes = []
def enter_proc(self, lineno):
""" Enters (pushes) a new context
"""
self.local_labels.append({}) # Add a new context
self.scopes.append(lineno)
__DEBUG__('Entering scope level %i at line %i' % (len(self.scopes), lineno))
def set_org(self, value, lineno):
""" Sets a new ORG value
"""
if value < 0 or value > MAX_MEM:
error(lineno, "Memory ORG out of range [0 .. 65535]. Current value: %i" % value)
self.index = self.ORG = value
@staticmethod
def id_name(label, namespace=None):
""" Given a name and a namespace, resolves
returns the name as namespace + '.' + name. If namespace
is none, the current NAMESPACE is used
"""
if not label.startswith(DOT):
if namespace is None:
namespace = NAMESPACE
ex_label = namespace + label # The mangled namespace.labelname label
else:
if namespace is None:
namespace = GLOBAL_NAMESPACE # Global namespace
ex_label = label
return ex_label, namespace
@property
def org(self):
""" Returns current ORG index
"""
return self.index
def __set_byte(self, byte, lineno):
""" Sets a byte at the current location,
and increments org in one. Raises an error if org > MAX_MEMORY
"""
if byte < 0 or byte > 255:
error(lineno, 'Invalid byte value %i' % byte)
self.memory_bytes[self.org] = byte
self.index += 1 # Increment current memory pointer
def exit_proc(self, lineno):
""" Exits current procedure. Local labels are transferred to global
scope unless they have been marked as local ones.
Raises an error if no current local context (stack underflow)
"""
__DEBUG__('Exiting current scope from lineno %i' % lineno)
if len(self.local_labels) <= 1:
error(lineno, 'ENDP in global scope (with no PROC)')
return
for label in self.local_labels[-1].values():
if label.local:
if not label.defined:
error(lineno, "Undefined LOCAL label '%s'" % label.name)
return
continue
name = label.name
_lineno = label.lineno
value = label.value
if name not in self.global_labels.keys():
self.global_labels[name] = label
else:
self.global_labels[name].define(value, _lineno)
self.local_labels.pop() # Removes current context
self.scopes.pop()
def set_memory_slot(self):
if self.org not in self.orgs.keys():
self.orgs[self.org] = () # Declares an empty memory slot if not already done
self.memory_bytes[self.org] = () # Declares an empty memory slot if not already done
def add_instruction(self, instr):
""" This will insert an asm instruction at the current memory position
in a t-uple as (mnemonic, params).
It will also insert the opcodes at the memory_bytes
"""
if gl.has_errors:
return
__DEBUG__('%04Xh [%04Xh] ASM: %s' % (self.org, self.org - self.ORG, instr.asm))
self.set_memory_slot()
self.orgs[self.org] += (instr,)
for byte in instr.bytes():
self.__set_byte(byte, instr.lineno)
def dump(self):
""" Returns a tuple containing code ORG (origin address), and a list of bytes (OUTPUT)
"""
org = min(self.memory_bytes.keys()) # Org is the lowest one
OUTPUT = []
align = []
for label in self.global_labels.values():
if not label.defined:
error(label.lineno, "Undefined GLOBAL label '%s'" % label.name)
for i in range(org, max(self.memory_bytes.keys()) + 1):
if gl.has_errors:
return org, OUTPUT
try:
try:
a = [x for x in self.orgs[i] if isinstance(x, Asm)] # search for asm instructions
if not a:
align.append(0) # Fill with ZEROes not used memory regions
continue
OUTPUT += align
align = []
a = a[0]
if a.pending:
a.arg = a.argval()
a.pending = False
tmp = a.bytes()
for r in range(len(tmp)):
self.memory_bytes[i + r] = tmp[r]
except KeyError:
pass
OUTPUT.append(self.memory_bytes[i])
except KeyError:
OUTPUT.append(0) # Fill with ZEROes not used memory regions
return org, OUTPUT
def declare_label(self, label, lineno, value=None, local=False, namespace=None):
""" Sets a label with the given value or with the current address (org)
if no value is passed.
Exits with error if label already set,
otherwise return the label object
"""
ex_label, namespace = Memory.id_name(label, namespace)
is_address = value is None
if value is None:
value = self.org
if ex_label in self.local_labels[-1].keys():
self.local_labels[-1][ex_label].define(value, lineno)
self.local_labels[-1][ex_label].is_address = is_address
else:
self.local_labels[-1][ex_label] = Label(ex_label, lineno, value, local, namespace, is_address)
self.set_memory_slot()
return self.local_labels[-1][ex_label]
def get_label(self, label, lineno):
""" Returns a label in the current context or in the global one.
If the label does not exists, creates a new one and returns it.
"""
global NAMESPACE
ex_label, namespace = Memory.id_name(label)
for i in range(len(self.local_labels) - 1, -1, -1): # Downstep
result = self.local_labels[i].get(ex_label, None)
if result is not None:
return result
result = Label(ex_label, lineno, namespace=namespace)
self.local_labels[-1][ex_label] = result # HINT: no namespace
return result
def set_label(self, label, lineno, local=False):
""" Sets a label, lineno and local flag in the current scope
(even if it exist in previous scopes). If the label exist in
the current scope, changes it flags.
The resulting label is returned.
"""
ex_label, namespace = Memory.id_name(label)
if ex_label in self.local_labels[-1].keys():
result = self.local_labels[-1][ex_label]
result.lineno = lineno
else:
result = self.local_labels[-1][ex_label] = Label(ex_label, lineno, namespace=NAMESPACE)
if result.local == local:
warning(lineno, "label '%s' already declared as LOCAL" % label)
result.local = local
return result
@property
def memory_map(self):
""" Returns a (very long) string containing a memory map
hex address: label
"""
return '\n'.join(sorted("%04X: %s" % (x.value, x.name) for x in self.global_labels.values() if x.is_address))
# -------- GRAMMAR RULES for the preprocessor ---------
def p_start(p):
""" start : program
| program endline
"""
def p_program_endline(p):
""" endline : END NEWLINE
"""
def p_program_endline2(p):
""" endline : END expr NEWLINE
| END pexpr NEWLINE
"""
global AUTORUN_ADDR
AUTORUN_ADDR = p[2].eval()
def p_program(p):
""" program : line
"""
def p_program_line(p):
""" program : program line
"""
def p_def_label(p):
""" line : ID EQU expr NEWLINE
| ID EQU pexpr NEWLINE
"""
p[0] = None
__DEBUG__("Declaring '%s%s' in %i" % (NAMESPACE, p[1], p.lineno(1)))
MEMORY.declare_label(p[1], p.lineno(1), p[3])
def p_line_asm(p):
""" line : asms NEWLINE
| asms CO NEWLINE
"""
def p_asms_empty(p):
""" asms :
"""
p[0] = MEMORY.org
def p_asms_asm(p):
""" asms : asm
"""
p[0] = MEMORY.org
asm = p[1]
if isinstance(asm, Asm):
MEMORY.add_instruction(asm)
def p_asms_asms_asm(p):
""" asms : asms CO asm
"""
p[0] = p[1]
asm = p[3]
if isinstance(asm, Asm):
MEMORY.add_instruction(asm)
def p_asm_label(p):
""" asm : ID
"""
__DEBUG__("Declaring '%s%s' (value %04Xh) in %i" % (NAMESPACE, p[1], MEMORY.org, p.lineno(1)))
MEMORY.declare_label(p[1], p.lineno(1))
def p_asm_ld8(p):
""" asm : LD reg8 COMMA reg8_hl
| LD reg8_hl COMMA reg8
| LD reg8 COMMA reg8
| LD SP COMMA HL
| LD SP COMMA reg16i
| LD A COMMA reg8
| LD reg8 COMMA A
| LD reg8_hl COMMA A
| LD A COMMA reg8_hl
| LD A COMMA A
| LD A COMMA I
| LD I COMMA A
| LD A COMMA R
| LD R COMMA A
| LD A COMMA reg8i
| LD reg8i COMMA A
| LD reg8 COMMA reg8i
| LD reg8i COMMA regBCDE
| LD reg8i COMMA reg8i
"""
if p[2] in ('H', 'L') and p[4] in ('IXH', 'IXL', 'IYH', 'IYL'):
p[0] = None
error(p.lineno(0), "Unexpected token '%s'" % p[4])
else:
p[0] = Asm(p.lineno(1), 'LD %s,%s' % (p[2], p[4]))
def p_LDa(p): # Remaining LD A,... and LD...,A instructions
""" asm : LD A COMMA LP BC RP
| LD A COMMA LP DE RP
| LD LP BC RP COMMA A
| LD LP DE RP COMMA A
"""
p[0] = Asm(p.lineno(1), 'LD ' + ''.join(p[2:]))
def p_PROC(p):
""" asm : PROC
"""
p[0] = None # Start of a PROC scope
MEMORY.enter_proc(p.lineno(1))
def p_ENDP(p):
""" asm : ENDP
"""
p[0] = None # End of a PROC scope
MEMORY.exit_proc(p.lineno(1))
def p_LOCAL(p):
""" asm : LOCAL id_list
"""
p[0] = None
for label, line in p[2]:
__DEBUG__("Setting label '%s' as local at line %i" % (label, line))
MEMORY.set_label(label, line, local=True)
def p_idlist(p):
""" id_list : ID
"""
p[0] = ((p[1], p.lineno(1)),)
def p_idlist_id(p):
""" id_list : id_list COMMA ID
"""
p[0] = p[1] + ((p[3], p.lineno(3)),)
def p_DEFB(p): # Define bytes
""" asm : DEFB expr_list
| DEFB number_list
"""
p[0] = Asm(p.lineno(1), 'DEFB', p[2])
def p_DEFS(p): # Define bytes
""" asm : DEFS number_list
"""
if len(p[2]) > 2:
error(p.lineno(1), "too many arguments for DEFS")
if len(p[2]) < 2:
num = Expr.makenode(Container(0, p.lineno(1))) # Defaults to 0
p[2] = p[2] + (num,)
p[0] = Asm(p.lineno(1), 'DEFS', p[2])
def p_DEFW(p): # Define words
""" asm : DEFW number_list
"""
p[0] = Asm(p.lineno(1), 'DEFW', p[2])
def p_expr_list_from_string(p):
""" expr_list : STRING
"""
p[0] = tuple(Expr.makenode(Container(ord(x), p.lineno(1))) for x in p[1])
def p_expr_list_plus_expr(p):
""" expr_list : expr_list COMMA expr
| expr_list COMMA pexpr
"""
p[0] = p[1] + (p[3],)
def p_expr_list_plus_string(p):
""" expr_list : expr_list COMMA STRING
"""
p[0] = p[1] + tuple(Expr.makenode(Container(ord(x), p.lineno(3))) for x in p[3])
def p_number_list(p):
""" number_list : expr
| pexpr
"""
p[0] = (p[1],)
def p_number_list_number(p):
""" number_list : number_list COMMA expr
| number_list COMMA pexpr
"""
p[0] = p[1] + (p[3],)
def p_asm_ldind_r8(p):
""" asm : LD reg8_I COMMA reg8
| LD reg8_I COMMA A
"""
p[0] = Asm(p.lineno(1), 'LD %s,%s' % (p[2][0], p[4]), p[2][1])
def p_asm_ldr8_ind(p):
""" asm : LD reg8 COMMA reg8_I
| LD A COMMA reg8_I
"""
p[0] = Asm(p.lineno(1), 'LD %s,%s' % (p[2], p[4][0]), p[4][1])
def p_reg8_hl(p):
""" reg8_hl : LP HL RP
"""
p[0] = '(HL)'
def p_ind8_I(p):
""" reg8_I : LP IX expr RP
| LP IY expr RP
| LP IX PLUS pexpr RP
| LP IX MINUS pexpr RP
| LP IY PLUS pexpr RP
| LP IY MINUS pexpr RP
"""
if len(p) == 6:
expr = p[4]
sign = p[3]
else:
expr = p[3]
gen_ = expr.inorder()
first_expr = next(gen_, '')
if first_expr and first_expr.parent:
if len(first_expr.parent.children) == 2:
first_token = first_expr.symbol.item
else:
first_token = first_expr.parent.symbol.item
else:
first_token = '<nothing>'
if first_token not in ('-', '+'):
error(p.lineno(2), "Unexpected token '{}'. Expected '+' or '-'".format(first_token))
sign = '+'
if sign == '-':
expr = Expr.makenode(Container(sign, p.lineno(2)), expr)
p[0] = ('(%s+N)' % p[2], expr)
def p_ex_af_af(p):
""" asm : EX AF COMMA AF APO
"""
p[0] = Asm(p.lineno(1), "EX AF,AF'")
def p_ex_de_hl(p):
""" asm : EX DE COMMA HL
"""
p[0] = Asm(p.lineno(1), "EX DE,HL")
def p_org(p):
""" asm : ORG expr
| ORG pexpr
"""
MEMORY.set_org(p[2].eval(), p.lineno(1))
def p_namespace(p):
""" asm : NAMESPACE ID
"""
global NAMESPACE
NAMESPACE = normalize_namespace(p[2])
__DEBUG__('Setting namespace to ' + (NAMESPACE.rstrip(DOT) or DOT), level=1)
def p_align(p):
""" asm : ALIGN expr
| ALIGN pexpr
"""
align = p[2].eval()
if align < 2:
error(p.lineno(1), "ALIGN value must be greater than 1")
return
MEMORY.set_org(MEMORY.org + (align - MEMORY.org % align) % align, p.lineno(1))
def p_incbin(p):
""" asm : INCBIN STRING
"""
try:
fname = zxbpp.search_filename(p[2], p.lineno(2), local_first=True)
if not fname:
p[0] = None
return
with api.utils.open_file(fname, 'rb') as f:
filecontent = f.read()
except IOError:
error(p.lineno(2), "cannot read file '%s'" % p[2])
p[0] = None
return
p[0] = Asm(p.lineno(1), 'DEFB', filecontent)
def p_ex_sp_reg8(p):
""" asm : EX LP SP RP COMMA reg16i
| EX LP SP RP COMMA HL
"""
p[0] = Asm(p.lineno(1), 'EX (SP),' + p[6])
def p_incdec(p):
""" asm : INC inc_reg
| DEC inc_reg
"""
p[0] = Asm(p.lineno(1), '%s %s' % (p[1], p[2]))
def p_incdeci(p):
""" asm : INC reg8_I
| DEC reg8_I
"""
p[0] = Asm(p.lineno(1), '%s %s' % (p[1], p[2][0]), p[2][1])
def p_LD_reg_val(p):
""" asm : LD reg8 COMMA expr
| LD reg8 COMMA pexpr
| LD reg16 COMMA expr
| LD reg8_hl COMMA expr
| LD A COMMA expr
| LD SP COMMA expr
| LD reg8i COMMA expr
"""
s = 'LD %s,N' % p[2]
if p[2] in REGS16:
s += 'N'
p[0] = Asm(p.lineno(1), s, p[4])
def p_LD_regI_val(p):
""" asm : LD reg8_I COMMA expr
"""
p[0] = Asm(p.lineno(1), 'LD %s,N' % p[2][0], (p[2][1], p[4]))
def p_JP_hl(p):
""" asm : JP reg8_hl
| JP LP reg16i RP
"""
s = 'JP '
if p[2] == '(HL)':
s += p[2]
else:
s += '(%s)' % p[3]
p[0] = Asm(p.lineno(1), s)
def p_SBCADD(p):
""" asm : SBC A COMMA reg8
| SBC A COMMA reg8i
| SBC A COMMA A
| SBC A COMMA reg8_hl
| SBC HL COMMA SP
| SBC HL COMMA BC
| SBC HL COMMA DE
| SBC HL COMMA HL
| ADD A COMMA reg8
| ADD A COMMA reg8i
| ADD A COMMA A
| ADD A COMMA reg8_hl
| ADC A COMMA reg8
| ADC A COMMA reg8i
| ADC A COMMA A
| ADC A COMMA reg8_hl
| ADD HL COMMA BC
| ADD HL COMMA DE
| ADD HL COMMA HL
| ADD HL COMMA SP
| ADC HL COMMA BC
| ADC HL COMMA DE
| ADC HL COMMA HL
| ADC HL COMMA SP
| ADD reg16i COMMA BC
| ADD reg16i COMMA DE
| ADD reg16i COMMA HL
| ADD reg16i COMMA SP
| ADD reg16i COMMA reg16i
"""
p[0] = Asm(p.lineno(1), '%s %s,%s' % (p[1], p[2], p[4]))
def p_arith_A_expr(p):
""" asm : SBC A COMMA expr
| SBC A COMMA pexpr
| ADD A COMMA expr
| ADD A COMMA pexpr
| ADC A COMMA expr
| ADC A COMMA pexpr
"""
p[0] = Asm(p.lineno(1), '%s A,N' % p[1], p[4])
def p_arith_A_regI(p):
""" asm : SBC A COMMA reg8_I
| ADD A COMMA reg8_I
| ADC A COMMA reg8_I
"""
p[0] = Asm(p.lineno(1), '%s A,%s' % (p[1], p[4][0]), p[4][1])
def p_bitwiseop_reg(p):
""" asm : bitwiseop reg8
| bitwiseop reg8i
| bitwiseop A
| bitwiseop reg8_hl
"""
p[0] = Asm(p[1][1], '%s %s' % (p[1][0], p[2]))
def p_bitwiseop_regI(p):
""" asm : bitwiseop reg8_I
"""
p[0] = Asm(p[1][1], '%s %s' % (p[1][0], p[2][0]), p[2][1])
def p_bitwise_expr(p):
""" asm : bitwiseop expr
| bitwiseop pexpr
"""
p[0] = Asm(p[1][1], '%s N' % p[1][0], p[2])
def p_bitwise(p):
""" bitwiseop : OR
| AND
| XOR
| SUB
| CP
"""
p[0] = (p[1], p.lineno(1))
def p_PUSH_POP(p):
""" asm : PUSH AF
| PUSH reg16
| POP AF
| POP reg16
"""
p[0] = Asm(p.lineno(1), '%s %s' % (p[1], p[2]))
def p_LD_addr_reg(p): # Load address,reg
""" asm : LD pexpr COMMA A
| LD pexpr COMMA reg16
| LD pexpr COMMA SP
"""
p[0] = Asm(p.lineno(1), 'LD (NN),%s' % p[4], p[2])
def p_LD_reg_addr(p): # Load address,reg
""" asm : LD A COMMA pexpr
| LD reg16 COMMA pexpr
| LD SP COMMA pexpr
"""
p[0] = Asm(p.lineno(1), 'LD %s,(NN)' % p[2], p[4])
def p_ROTATE(p):
""" asm : rotation reg8
| rotation reg8_hl
| rotation A
"""
p[0] = Asm(p[1][1], '%s %s' % (p[1][0], p[2]))
def p_ROTATE_ix(p):
""" asm : rotation reg8_I
"""
p[0] = Asm(p[1][1], '%s %s' % (p[1][0], p[2][0]), p[2][1])
def p_BIT(p):
""" asm : bitop expr COMMA A
| bitop pexpr COMMA A
| bitop expr COMMA reg8
| bitop pexpr COMMA reg8
| bitop expr COMMA reg8_hl
| bitop pexpr COMMA reg8_hl
"""
bit = p[2].eval()
if bit < 0 or bit > 7:
error(p.lineno(3), 'Invalid bit position %i. Must be in [0..7]' % bit)
p[0] = None
return
p[0] = Asm(p.lineno(3), '%s %i,%s' % (p[1], bit, p[4]))
def p_BIT_ix(p):
""" asm : bitop expr COMMA reg8_I
| bitop pexpr COMMA reg8_I
"""
bit = p[2].eval()
if bit < 0 or bit > 7:
error(p.lineno(3), 'Invalid bit position %i. Must be in [0..7]' % bit)
p[0] = None
return
p[0] = Asm(p.lineno(3), '%s %i,%s' % (p[1], bit, p[4][0]), p[4][1])
def p_bitop(p):
""" bitop : BIT
| RES
| SET
"""
p[0] = p[1]
def p_rotation(p):
""" rotation : RR
| RL
| RRC
| RLC
| SLA
| SLL
| SRA
| SRL
"""
p[0] = (p[1], p.lineno(1))
def p_reg_inc(p): # INC/DEC registers and (HL)
""" inc_reg : SP
| reg8
| reg16
| reg8_hl
| A
| reg8i
"""
p[0] = p[1]
def p_reg8(p):
""" reg8 : H
| L
| regBCDE
"""
p[0] = p[1]
def p_regBCDE(p):
""" regBCDE : B
| C
| D
| E
"""
p[0] = p[1]
def p_reg8i(p):
""" reg8i : IXH
| IXL
| IYH
| IYL
"""
p[0] = p[1]
def p_reg16(p):
""" reg16 : BC
| DE
| HL
| reg16i
"""
p[0] = p[1]
def p_reg16i(p):
""" reg16i : IX
| IY
"""
p[0] = p[1]
def p_jp(p):
""" asm : JP jp_flags COMMA expr
| JP jp_flags COMMA pexpr
| CALL jp_flags COMMA expr
| CALL jp_flags COMMA pexpr
"""
p[0] = Asm(p.lineno(1), '%s %s,NN' % (p[1], p[2]), p[4])
def p_ret(p):
""" asm : RET jp_flags
"""
p[0] = Asm(p.lineno(1), 'RET %s' % p[2])
def p_jpflags_other(p):
""" jp_flags : P
| M
| PO
| PE
| jr_flags
"""
p[0] = p[1]
def p_jr(p):
""" asm : JR jr_flags COMMA expr
| JR jr_flags COMMA pexpr
"""
p[4] = Expr.makenode(Container('-', p.lineno(3)), p[4], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1))))
p[0] = Asm(p.lineno(1), 'JR %s,N' % p[2], p[4])
def p_jr_flags(p):
""" jr_flags : Z
| C
| NZ
| NC
"""
p[0] = p[1]
def p_jrjp(p):
""" asm : JP expr
| JR expr
| CALL expr
| DJNZ expr
| JP pexpr
| JR pexpr
| CALL pexpr
| DJNZ pexpr
"""
if p[1] in ('JR', 'DJNZ'):
op = 'N'
p[2] = Expr.makenode(Container('-', p.lineno(1)), p[2], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1))))
else:
op = 'NN'
p[0] = Asm(p.lineno(1), p[1] + ' ' + op, p[2])
def p_rst(p):
""" asm : RST expr
"""
val = p[2].eval()
if val not in (0, 8, 16, 24, 32, 40, 48, 56):
error(p.lineno(1), 'Invalid RST number %i' % val)
p[0] = None
return
p[0] = Asm(p.lineno(1), 'RST %XH' % val)
def p_im(p):
""" asm : IM expr
"""
val = p[2].eval()
if val not in (0, 1, 2):
error(p.lineno(1), 'Invalid IM number %i' % val)
p[0] = None
return
p[0] = Asm(p.lineno(1), 'IM %i' % val)
def p_in(p):
""" asm : IN A COMMA LP C RP
| IN reg8 COMMA LP C RP
"""
p[0] = Asm(p.lineno(1), 'IN %s,(C)' % p[2])
def p_out(p):
""" asm : OUT LP C RP COMMA A
| OUT LP C RP COMMA reg8
"""
p[0] = Asm(p.lineno(1), 'OUT (C),%s' % p[6])
def p_in_expr(p):
""" asm : IN A COMMA pexpr
"""
p[0] = Asm(p.lineno(1), 'IN A,(N)', p[4])
def p_out_expr(p):
""" asm : OUT pexpr COMMA A
"""
p[0] = Asm(p.lineno(1), 'OUT (N),A', p[2])
def p_single(p):
""" asm : NOP
| EXX
| CCF
| SCF
| LDIR
| LDI
| LDDR
| LDD
| CPIR
| CPI
| CPDR
| CPD
| DAA
| NEG
| CPL
| HALT
| EI
| DI
| OUTD
| OUTI
| OTDR
| OTIR
| IND
| INI
| INDR
| INIR
| RET
| RETI
| RETN
| RLA
| RLCA
| RRA
| RRCA
| RLD
| RRD
"""
p[0] = Asm(p.lineno(1), p[1]) # Single instruction
def p_expr_div_expr(p):
""" expr : expr BAND expr
| expr BOR expr
| expr BXOR expr
| expr PLUS expr
| expr MINUS expr
| expr MUL expr
| expr DIV expr
| expr MOD expr
| expr POW expr
| expr LSHIFT expr
| expr RSHIFT expr
| pexpr BAND expr
| pexpr BOR expr
| pexpr BXOR expr
| pexpr PLUS expr
| pexpr MINUS expr
| pexpr MUL expr
| pexpr DIV expr
| pexpr MOD expr
| pexpr POW expr
| pexpr LSHIFT expr
| pexpr RSHIFT expr
| expr BAND pexpr
| expr BOR pexpr
| expr BXOR pexpr
| expr PLUS pexpr
| expr MINUS pexpr
| expr MUL pexpr
| expr DIV pexpr
| expr MOD pexpr
| expr POW pexpr
| expr LSHIFT pexpr
| expr RSHIFT pexpr
| pexpr BAND pexpr
| pexpr BOR pexpr
| pexpr BXOR pexpr
| pexpr PLUS pexpr
| pexpr MINUS pexpr
| pexpr MUL pexpr
| pexpr DIV pexpr
| pexpr MOD pexpr
| pexpr POW pexpr
| pexpr LSHIFT pexpr
| pexpr RSHIFT pexpr
"""
p[0] = Expr.makenode(Container(p[2], p.lineno(2)), p[1], p[3])
def p_expr_lprp(p):
""" pexpr : LP expr RP
"""
p[0] = p[2]
def p_expr_uminus(p):
""" expr : MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
"""
p[0] = Expr.makenode(Container(p[1], p.lineno(1)), p[2])
def p_expr_int(p):
""" expr : INTEGER
"""
p[0] = Expr.makenode(Container(int(p[1]), p.lineno(1)))
def p_expr_label(p):
""" expr : ID
"""
p[0] = Expr.makenode(Container(MEMORY.get_label(p[1], p.lineno(1)), p.lineno(1)))
def p_expr_paren(p):
""" expr : LPP expr RPP
"""
p[0] = p[2]
def p_expr_addr(p):
""" expr : ADDR
"""
# The current instruction address
p[0] = Expr.makenode(Container(MEMORY.org, p.lineno(1)))
# Some preprocessor directives
def p_preprocessor_line(p):
""" line : preproc_line
"""
p[0] = None
def p_preprocessor_line_line(p):
""" preproc_line : _LINE INTEGER
"""
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(2)
def p_preprocessor_line_line_file(p):
""" preproc_line : _LINE INTEGER STRING
"""
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1
gl.FILENAME = p[3]
def p_preproc_line_init(p):
""" preproc_line : _INIT ID
"""
INITS.append((p[2], p.lineno(2)))
# --- YYERROR
def p_error(p):
if p is not None:
if p.type != 'NEWLINE':
error(p.lineno, "Syntax error. Unexpected token '%s' [%s]" % (p.value, p.type))
else:
error(p.lineno, "Syntax error. Unexpected end of line [NEWLINE]")
else:
OPTIONS.stderr.value.write("General syntax error at assembler (unexpected End of File?)")
gl.has_errors += 1
def assemble(input_):
""" Assembles input string, and leave the result in the
MEMORY global object
"""
global MEMORY
if MEMORY is None:
MEMORY = Memory()
if OPTIONS.zxnext.value:
parser_ = zxnext_parser
else:
parser_ = parser
parser_.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 1)
if len(MEMORY.scopes):
error(MEMORY.scopes[-1], 'Missing ENDP to close this scope')
return gl.has_errors
def generate_binary(outputfname, format_, progname='', binary_files=None, headless_binary_files=None,
emitter=None):
""" Outputs the memory binary to the
output filename using one of the given
formats: tap, tzx or bin
"""
global AUTORUN_ADDR
org, binary = MEMORY.dump()
if gl.has_errors:
return
if binary_files is None:
binary_files = []
if headless_binary_files is None:
headless_binary_files = []
bin_blocks = []
for fname in binary_files:
with api.utils.open_file(fname) as f:
bin_blocks.append((os.path.basename(fname), f.read()))
headless_bin_blocks = []
for fname in headless_binary_files:
with api.utils.open_file(fname) as f:
headless_bin_blocks.append(f.read())
if AUTORUN_ADDR is None:
AUTORUN_ADDR = org
if not progname:
progname = os.path.basename(outputfname)[:10]
if OPTIONS.use_loader.value:
program = basic.Basic()
if org > 16383: # Only for zx48k: CLEAR if above 16383
program.add_line([['CLEAR', org - 1]])
program.add_line([['LOAD', '""', program.token('CODE')]])
if OPTIONS.autorun.value:
program.add_line([['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]])
else:
program.add_line([['REM'], ['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]])
if emitter is None:
if format_ in ('tap', 'tzx'):
emitter = {'tap': outfmt.TAP, 'tzx': outfmt.TZX}[format_]()
else:
emitter = outfmt.BinaryEmitter()
loader_bytes = None
if OPTIONS.use_loader.value:
loader_bytes = program.bytes
assert isinstance(emitter, outfmt.CodeEmitter)
emitter.emit(output_filename=outputfname,
program_name=progname,
loader_bytes=loader_bytes,
entry_point=AUTORUN_ADDR,
program_bytes=binary,
aux_bin_blocks=bin_blocks,
aux_headless_bin_blocks=headless_bin_blocks)
def main(argv):
""" This is a test and will assemble the file in argv[0]
"""
init()
if OPTIONS.StdErrFileName.value:
OPTIONS.stderr.value = open('wt', OPTIONS.StdErrFileName.value)
asmlex.FILENAME = OPTIONS.inputFileName.value = argv[0]
input_ = open(OPTIONS.inputFileName.value, 'rt').read()
assemble(input_)
generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type)
# Z80 only ASM parser
parser = api.utils.get_or_create('asmparse', lambda: yacc.yacc(start="start", debug=True))
# needed for ply
from .zxnext import * # noqa
# ZXNEXT extended Opcodes parser
zxnext_parser = api.utils.get_or_create('zxnext_asmparse', lambda: yacc.yacc(start="start", debug=True))
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/asmparse.py
|
asmparse.py
|
from .zxbasm import main # noqa
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/__init__.py
|
__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:
class Opcode:
""" Describes opcodes and other info.
"""
def __init__(self, asm: str, time: int, size: int, opcode: str):
self.asm = asm
self.T = time
self.size = size
self.opcode = opcode
Z80SET = {
"ADC A,(HL)": Opcode("ADC A,(HL)", 7, 1, "8E"),
"ADC A,(IX+N)": Opcode("ADC A,(IX+N)", 19, 3, "DD 8E XX"),
"ADC A,(IY+N)": Opcode("ADC A,(IY+N)", 19, 3, "FD 8E XX"),
"ADC A,A": Opcode("ADC A,A", 4, 1, "8F"),
"ADC A,C": Opcode("ADC A,C", 4, 1, "89"),
"ADC A,B": Opcode("ADC A,B", 4, 1, "88"),
"ADC A,E": Opcode("ADC A,E", 4, 1, "8B"),
"ADC A,D": Opcode("ADC A,D", 4, 1, "8A"),
"ADC A,H": Opcode("ADC A,H", 4, 1, "8C"),
"ADC A,L": Opcode("ADC A,L", 4, 1, "8D"),
"ADC A,N": Opcode("ADC A,N", 7, 2, "CE XX"),
"ADC HL,BC": Opcode("ADC HL,BC", 15, 2, "ED 4A"),
"ADC HL,DE": Opcode("ADC HL,DE", 15, 2, "ED 5A"),
"ADC HL,HL": Opcode("ADC HL,HL", 15, 2, "ED 6A"),
"ADC HL,SP": Opcode("ADC HL,SP", 15, 2, "ED 7A"),
"ADD A,(HL)": Opcode("ADD A,(HL)", 7, 1, "86"),
"ADD A,(IX+N)": Opcode("ADD A,(IX+N)", 19, 3, "DD 86 XX"),
"ADD A,(IY+N)": Opcode("ADD A,(IY+N)", 19, 3, "FD 86 XX"),
"ADD A,A": Opcode("ADD A,A", 4, 1, "87"),
"ADD A,C": Opcode("ADD A,C", 4, 1, "81"),
"ADD A,B": Opcode("ADD A,B", 4, 1, "80"),
"ADD A,E": Opcode("ADD A,E", 4, 1, "83"),
"ADD A,D": Opcode("ADD A,D", 4, 1, "82"),
"ADD A,H": Opcode("ADD A,H", 4, 1, "84"),
"ADD A,L": Opcode("ADD A,L", 4, 1, "85"),
"ADD A,N": Opcode("ADD A,N", 7, 2, "C6 XX"),
"ADD HL,BC": Opcode("ADD HL,BC", 11, 1, "09"),
"ADD HL,DE": Opcode("ADD HL,DE", 11, 1, "19"),
"ADD HL,HL": Opcode("ADD HL,HL", 11, 1, "29"),
"ADD HL,SP": Opcode("ADD HL,SP", 11, 1, "39"),
"ADD IX,BC": Opcode("ADD IX,BC", 15, 2, "DD 09"),
"ADD IX,DE": Opcode("ADD IX,DE", 15, 2, "DD 19"),
"ADD IX,IX": Opcode("ADD IX,IX", 15, 2, "DD 29"),
"ADD IX,SP": Opcode("ADD IX,SP", 15, 2, "DD 39"),
"ADD IY,BC": Opcode("ADD IY,BC", 15, 2, "FD 09"),
"ADD IY,DE": Opcode("ADD IY,DE", 15, 2, "FD 19"),
"ADD IY,IY": Opcode("ADD IY,IY", 15, 2, "FD 29"),
"ADD IY,SP": Opcode("ADD IY,SP", 15, 2, "FD 39"),
"AND (HL)": Opcode("AND (HL)", 7, 1, "A6"),
"AND (IX+N)": Opcode("AND (IX+N)", 19, 3, "DD A6 XX"),
"AND (IY+N)": Opcode("AND (IY+N)", 19, 3, "FD A6 XX"),
"AND A": Opcode("AND A", 4, 1, "A7"),
"AND C": Opcode("AND C", 4, 1, "A1"),
"AND B": Opcode("AND B", 4, 1, "A0"),
"AND E": Opcode("AND E", 4, 1, "A3"),
"AND D": Opcode("AND D", 4, 1, "A2"),
"AND H": Opcode("AND H", 4, 1, "A4"),
"AND L": Opcode("AND L", 4, 1, "A5"),
"AND N": Opcode("AND N", 7, 2, "E6 XX"),
"BIT 0,(HL)": Opcode("BIT 0,(HL)", 12, 2, "CB 46"),
"BIT 1,(HL)": Opcode("BIT 1,(HL)", 12, 2, "CB 4E"),
"BIT 2,(HL)": Opcode("BIT 2,(HL)", 12, 2, "CB 56"),
"BIT 3,(HL)": Opcode("BIT 3,(HL)", 12, 2, "CB 5E"),
"BIT 4,(HL)": Opcode("BIT 4,(HL)", 12, 2, "CB 66"),
"BIT 5,(HL)": Opcode("BIT 5,(HL)", 12, 2, "CB 6E"),
"BIT 6,(HL)": Opcode("BIT 6,(HL)", 12, 2, "CB 76"),
"BIT 7,(HL)": Opcode("BIT 7,(HL)", 12, 2, "CB 7E"),
"BIT 0,(IX+N)": Opcode("BIT 0,(IX+N)", 20, 4, "DD CB XX 46"),
"BIT 1,(IX+N)": Opcode("BIT 1,(IX+N)", 20, 4, "DD CB XX 4E"),
"BIT 2,(IX+N)": Opcode("BIT 2,(IX+N)", 20, 4, "DD CB XX 56"),
"BIT 3,(IX+N)": Opcode("BIT 3,(IX+N)", 20, 4, "DD CB XX 5E"),
"BIT 4,(IX+N)": Opcode("BIT 4,(IX+N)", 20, 4, "DD CB XX 66"),
"BIT 5,(IX+N)": Opcode("BIT 5,(IX+N)", 20, 4, "DD CB XX 6E"),
"BIT 6,(IX+N)": Opcode("BIT 6,(IX+N)", 20, 4, "DD CB XX 76"),
"BIT 7,(IX+N)": Opcode("BIT 7,(IX+N)", 20, 4, "DD CB XX 7E"),
"BIT 0,(IY+N)": Opcode("BIT 0,(IY+N)", 20, 4, "FD CB XX 46"),
"BIT 1,(IY+N)": Opcode("BIT 1,(IY+N)", 20, 4, "FD CB XX 4E"),
"BIT 2,(IY+N)": Opcode("BIT 2,(IY+N)", 20, 4, "FD CB XX 56"),
"BIT 3,(IY+N)": Opcode("BIT 3,(IY+N)", 20, 4, "FD CB XX 5E"),
"BIT 4,(IY+N)": Opcode("BIT 4,(IY+N)", 20, 4, "FD CB XX 66"),
"BIT 5,(IY+N)": Opcode("BIT 5,(IY+N)", 20, 4, "FD CB XX 6E"),
"BIT 6,(IY+N)": Opcode("BIT 6,(IY+N)", 20, 4, "FD CB XX 76"),
"BIT 7,(IY+N)": Opcode("BIT 7,(IY+N)", 20, 4, "FD CB XX 7E"),
"BIT 0,A": Opcode("BIT 0,A", 8, 2, "CB 47"),
"BIT 1,A": Opcode("BIT 1,A", 8, 2, "CB 4F"),
"BIT 2,A": Opcode("BIT 2,A", 8, 2, "CB 57"),
"BIT 3,A": Opcode("BIT 3,A", 8, 2, "CB 5F"),
"BIT 4,A": Opcode("BIT 4,A", 8, 2, "CB 67"),
"BIT 5,A": Opcode("BIT 5,A", 8, 2, "CB 6F"),
"BIT 6,A": Opcode("BIT 6,A", 8, 2, "CB 77"),
"BIT 7,A": Opcode("BIT 7,A", 8, 2, "CB 7F"),
"BIT 0,C": Opcode("BIT 0,C", 8, 2, "CB 41"),
"BIT 1,C": Opcode("BIT 1,C", 8, 2, "CB 49"),
"BIT 2,C": Opcode("BIT 2,C", 8, 2, "CB 51"),
"BIT 3,C": Opcode("BIT 3,C", 8, 2, "CB 59"),
"BIT 4,C": Opcode("BIT 4,C", 8, 2, "CB 61"),
"BIT 5,C": Opcode("BIT 5,C", 8, 2, "CB 69"),
"BIT 6,C": Opcode("BIT 6,C", 8, 2, "CB 71"),
"BIT 7,C": Opcode("BIT 7,C", 8, 2, "CB 79"),
"BIT 0,B": Opcode("BIT 0,B", 8, 2, "CB 40"),
"BIT 1,B": Opcode("BIT 1,B", 8, 2, "CB 48"),
"BIT 2,B": Opcode("BIT 2,B", 8, 2, "CB 50"),
"BIT 3,B": Opcode("BIT 3,B", 8, 2, "CB 58"),
"BIT 4,B": Opcode("BIT 4,B", 8, 2, "CB 60"),
"BIT 5,B": Opcode("BIT 5,B", 8, 2, "CB 68"),
"BIT 6,B": Opcode("BIT 6,B", 8, 2, "CB 70"),
"BIT 7,B": Opcode("BIT 7,B", 8, 2, "CB 78"),
"BIT 0,E": Opcode("BIT 0,E", 8, 2, "CB 43"),
"BIT 1,E": Opcode("BIT 1,E", 8, 2, "CB 4B"),
"BIT 2,E": Opcode("BIT 2,E", 8, 2, "CB 53"),
"BIT 3,E": Opcode("BIT 3,E", 8, 2, "CB 5B"),
"BIT 4,E": Opcode("BIT 4,E", 8, 2, "CB 63"),
"BIT 5,E": Opcode("BIT 5,E", 8, 2, "CB 6B"),
"BIT 6,E": Opcode("BIT 6,E", 8, 2, "CB 73"),
"BIT 7,E": Opcode("BIT 7,E", 8, 2, "CB 7B"),
"BIT 0,D": Opcode("BIT 0,D", 8, 2, "CB 42"),
"BIT 1,D": Opcode("BIT 1,D", 8, 2, "CB 4A"),
"BIT 2,D": Opcode("BIT 2,D", 8, 2, "CB 52"),
"BIT 3,D": Opcode("BIT 3,D", 8, 2, "CB 5A"),
"BIT 4,D": Opcode("BIT 4,D", 8, 2, "CB 62"),
"BIT 5,D": Opcode("BIT 5,D", 8, 2, "CB 6A"),
"BIT 6,D": Opcode("BIT 6,D", 8, 2, "CB 72"),
"BIT 7,D": Opcode("BIT 7,D", 8, 2, "CB 7A"),
"BIT 0,H": Opcode("BIT 0,H", 8, 2, "CB 44"),
"BIT 1,H": Opcode("BIT 1,H", 8, 2, "CB 4C"),
"BIT 2,H": Opcode("BIT 2,H", 8, 2, "CB 54"),
"BIT 3,H": Opcode("BIT 3,H", 8, 2, "CB 5C"),
"BIT 4,H": Opcode("BIT 4,H", 8, 2, "CB 64"),
"BIT 5,H": Opcode("BIT 5,H", 8, 2, "CB 6C"),
"BIT 6,H": Opcode("BIT 6,H", 8, 2, "CB 74"),
"BIT 7,H": Opcode("BIT 7,H", 8, 2, "CB 7C"),
"BIT 0,L": Opcode("BIT 0,L", 8, 2, "CB 45"),
"BIT 1,L": Opcode("BIT 1,L", 8, 2, "CB 4D"),
"BIT 2,L": Opcode("BIT 2,L", 8, 2, "CB 55"),
"BIT 3,L": Opcode("BIT 3,L", 8, 2, "CB 5D"),
"BIT 4,L": Opcode("BIT 4,L", 8, 2, "CB 65"),
"BIT 5,L": Opcode("BIT 5,L", 8, 2, "CB 6D"),
"BIT 6,L": Opcode("BIT 6,L", 8, 2, "CB 75"),
"BIT 7,L": Opcode("BIT 7,L", 8, 2, "CB 7D"),
"CALL C,NN": Opcode("CALL C,NN", 17, 3, "DC XX XX"),
"CALL M,NN": Opcode("CALL M,NN", 17, 3, "FC XX XX"),
"CALL NC,NN": Opcode("CALL NC,NN", 17, 3, "D4 XX XX"),
"CALL NN": Opcode("CALL NN", 17, 3, "CD XX XX"),
"CALL NZ,NN": Opcode("CALL NZ,NN", 17, 3, "C4 XX XX"),
"CALL P,NN": Opcode("CALL P,NN", 17, 3, "F4 XX XX"),
"CALL PE,NN": Opcode("CALL PE,NN", 17, 3, "EC XX XX"),
"CALL PO,NN": Opcode("CALL PO,NN", 17, 3, "E4 XX XX"),
"CALL Z,NN": Opcode("CALL Z,NN", 17, 3, "CC XX XX"),
"CCF": Opcode("CCF", 4, 1, "3F"),
"CP (HL)": Opcode("CP (HL)", 7, 1, "BE"),
"CP (IX+N)": Opcode("CP (IX+N)", 19, 3, "DD BE XX"),
"CP (IY+N)": Opcode("CP (IY+N)", 19, 3, "FD BE XX"),
"CP A": Opcode("CP A", 4, 1, "BF"),
"CP C": Opcode("CP C", 4, 1, "B9"),
"CP B": Opcode("CP B", 4, 1, "B8"),
"CP E": Opcode("CP E", 4, 1, "BB"),
"CP D": Opcode("CP D", 4, 1, "BA"),
"CP H": Opcode("CP H", 4, 1, "BC"),
"CP L": Opcode("CP L", 4, 1, "BD"),
"CP N": Opcode("CP N", 7, 2, "FE XX"),
"CPD": Opcode("CPD", 16, 2, "ED A9"),
"CPDR": Opcode("CPDR", 21, 2, "ED B9"),
"CPI": Opcode("CPI", 16, 2, "ED A1"),
"CPIR": Opcode("CPIR", 21, 2, "ED B1"),
"CPL": Opcode("CPL", 4, 1, "2F"),
"DAA": Opcode("DAA", 4, 1, "27"),
"DEC (HL)": Opcode("DEC (HL)", 11, 1, "35"),
"DEC (IX+N)": Opcode("DEC (IX+N)", 23, 3, "DD 35 XX"),
"DEC (IY+N)": Opcode("DEC (IY+N)", 23, 3, "FD 35 XX"),
"DEC A": Opcode("DEC A", 4, 1, "3D"),
"DEC B": Opcode("DEC B", 4, 1, "05"),
"DEC BC": Opcode("DEC BC", 6, 1, "0B"),
"DEC C": Opcode("DEC C", 4, 1, "0D"),
"DEC D": Opcode("DEC D", 4, 1, "15"),
"DEC DE": Opcode("DEC DE", 6, 1, "1B"),
"DEC E": Opcode("DEC E", 4, 1, "1D"),
"DEC H": Opcode("DEC H", 4, 1, "25"),
"DEC HL": Opcode("DEC HL", 6, 1, "2B"),
"DEC IX": Opcode("DEC IX", 10, 2, "DD 2B"),
"DEC IY": Opcode("DEC IY", 10, 2, "FD 2B"),
"DEC L": Opcode("DEC L", 4, 1, "2D"),
"DEC SP": Opcode("DEC SP", 6, 1, "3B"),
"DI": Opcode("DI", 4, 1, "F3"),
"DJNZ N": Opcode("DJNZ N", 13, 2, "10 XX"),
"EI": Opcode("EI", 4, 1, "FB"),
"EX (SP),HL": Opcode("EX (SP),HL", 19, 1, "E3"),
"EX (SP),IX": Opcode("EX (SP),IX", 23, 2, "DD E3"),
"EX (SP),IY": Opcode("EX (SP),IY", 23, 2, "FD E3"),
"EX AF,AF'": Opcode("EX AF,AF'", 4, 1, "08"),
"EX DE,HL": Opcode("EX DE,HL", 4, 1, "EB"),
"EXX": Opcode("EXX", 4, 1, "D9"),
"HALT": Opcode("HALT", 4, 1, "76"),
"IM 0": Opcode("IM 0", 8, 2, "ED 46"),
"IM 1": Opcode("IM 1", 8, 2, "ED 56"),
"IM 2": Opcode("IM 2", 8, 2, "ED 5E"),
"IN A,(C)": Opcode("IN A,(C)", 12, 2, "ED 78"),
"IN A,(N)": Opcode("IN A,(N)", 11, 2, "DB XX"),
"IN B,(C)": Opcode("IN B,(C)", 12, 2, "ED 40"),
"IN C,(C)": Opcode("IN C,(C)", 12, 2, "ED 48"),
"IN D,(C)": Opcode("IN D,(C)", 12, 2, "ED 50"),
"IN E,(C)": Opcode("IN E,(C)", 12, 2, "ED 58"),
"IN H,(C)": Opcode("IN H,(C)", 12, 2, "ED 60"),
"IN L,(C)": Opcode("IN L,(C)", 12, 2, "ED 68"),
"INC (HL)": Opcode("INC (HL)", 11, 1, "34"),
"INC (IX+N)": Opcode("INC (IX+N)", 23, 3, "DD 34 XX"),
"INC (IY+N)": Opcode("INC (IY+N)", 23, 3, "FD 34 XX"),
"INC A": Opcode("INC A", 4, 1, "3C"),
"INC B": Opcode("INC B", 4, 1, "04"),
"INC BC": Opcode("INC BC", 6, 1, "03"),
"INC C": Opcode("INC C", 4, 1, "0C"),
"INC D": Opcode("INC D", 4, 1, "14"),
"INC DE": Opcode("INC DE", 6, 1, "13"),
"INC E": Opcode("INC E", 4, 1, "1C"),
"INC H": Opcode("INC H", 4, 1, "24"),
"INC HL": Opcode("INC HL", 6, 1, "23"),
"INC IX": Opcode("INC IX", 10, 2, "DD 23"),
"INC IY": Opcode("INC IY", 10, 2, "FD 23"),
"INC L": Opcode("INC L", 4, 1, "2C"),
"INC SP": Opcode("INC SP", 6, 1, "33"),
"IND": Opcode("IND", 16, 2, "ED AA"),
"INDR": Opcode("INDR", 21, 2, "ED BA"),
"INI": Opcode("INI", 16, 2, "ED A2"),
"INIR": Opcode("INIR", 21, 2, "ED B2"),
"JP NN": Opcode("JP NN", 10, 3, "C3 XX XX"),
"JP (HL)": Opcode("JP (HL)", 4, 1, "E9"),
"JP (IX)": Opcode("JP (IX)", 8, 2, "DD E9"),
"JP (IY)": Opcode("JP (IY)", 8, 2, "FD E9"),
"JP C,NN": Opcode("JP C,NN", 10, 3, "DA XX XX"),
"JP M,NN": Opcode("JP M,NN", 10, 3, "FA XX XX"),
"JP NC,NN": Opcode("JP NC,NN", 10, 3, "D2 XX XX"),
"JP NZ,NN": Opcode("JP NZ,NN", 10, 3, "C2 XX XX"),
"JP P,NN": Opcode("JP P,NN", 10, 3, "F2 XX XX"),
"JP PE,NN": Opcode("JP PE,NN", 10, 3, "EA XX XX"),
"JP PO,NN": Opcode("JP PO,NN", 10, 3, "E2 XX XX"),
"JP Z,NN": Opcode("JP Z,NN", 10, 3, "CA XX XX"),
"JR N": Opcode("JR N", 12, 2, "18 XX"),
"JR C,N": Opcode("JR C,N", 12, 2, "38 XX"),
"JR NC,N": Opcode("JR NC,N", 12, 2, "30 XX"),
"JR NZ,N": Opcode("JR NZ,N", 12, 2, "20 XX"),
"JR Z,N": Opcode("JR Z,N", 12, 2, "28 XX"),
"LD (BC),A": Opcode("LD (BC),A", 7, 1, "02"),
"LD (DE),A": Opcode("LD (DE),A", 7, 1, "12"),
"LD (HL),A": Opcode("LD (HL),A", 7, 1, "77"),
"LD (HL),C": Opcode("LD (HL),C", 7, 1, "71"),
"LD (HL),B": Opcode("LD (HL),B", 7, 1, "70"),
"LD (HL),E": Opcode("LD (HL),E", 7, 1, "73"),
"LD (HL),D": Opcode("LD (HL),D", 7, 1, "72"),
"LD (HL),H": Opcode("LD (HL),H", 7, 1, "74"),
"LD (HL),L": Opcode("LD (HL),L", 7, 1, "75"),
"LD (HL),N": Opcode("LD (HL),N", 10, 2, "36 XX"),
"LD (IX+N),A": Opcode("LD (IX+N),A", 19, 3, "DD 77 XX"),
"LD (IX+N),C": Opcode("LD (IX+N),C", 19, 3, "DD 71 XX"),
"LD (IX+N),B": Opcode("LD (IX+N),B", 19, 3, "DD 70 XX"),
"LD (IX+N),E": Opcode("LD (IX+N),E", 19, 3, "DD 73 XX"),
"LD (IX+N),D": Opcode("LD (IX+N),D", 19, 3, "DD 72 XX"),
"LD (IX+N),H": Opcode("LD (IX+N),H", 19, 3, "DD 74 XX"),
"LD (IX+N),L": Opcode("LD (IX+N),L", 19, 3, "DD 75 XX"),
"LD (IX+N),N": Opcode("LD (IX+N),N", 19, 4, "DD 36 XX XX"),
"LD (IY+N),A": Opcode("LD (IY+N),A", 19, 3, "FD 77 XX"),
"LD (IY+N),C": Opcode("LD (IY+N),C", 19, 3, "FD 71 XX"),
"LD (IY+N),B": Opcode("LD (IY+N),B", 19, 3, "FD 70 XX"),
"LD (IY+N),E": Opcode("LD (IY+N),E", 19, 3, "FD 73 XX"),
"LD (IY+N),D": Opcode("LD (IY+N),D", 19, 3, "FD 72 XX"),
"LD (IY+N),H": Opcode("LD (IY+N),H", 19, 3, "FD 74 XX"),
"LD (IY+N),L": Opcode("LD (IY+N),L", 19, 3, "FD 75 XX"),
"LD (IY+N),N": Opcode("LD (IY+N),N", 19, 4, "FD 36 XX XX"),
"LD (NN),A": Opcode("LD (NN),A", 13, 3, "32 XX XX"),
"LD (NN),BC": Opcode("LD (NN),BC", 20, 4, "ED 43 XX XX"),
"LD (NN),DE": Opcode("LD (NN),DE", 20, 4, "ED 53 XX XX"),
"LD (NN),HL": Opcode("LD (NN),HL", 16, 3, "22 XX XX"),
"LD (NN),IX": Opcode("LD (NN),IX", 20, 4, "DD 22 XX XX"),
"LD (NN),IY": Opcode("LD (NN),IY", 20, 4, "FD 22 XX XX"),
"LD (NN),SP": Opcode("LD (NN),SP", 20, 4, "ED 73 XX XX"),
"LD A,(BC)": Opcode("LD A,(BC)", 7, 1, "0A"),
"LD A,(DE)": Opcode("LD A,(DE)", 7, 1, "1A"),
"LD A,(HL)": Opcode("LD A,(HL)", 7, 1, "7E"),
"LD A,(IX+N)": Opcode("LD A,(IX+N)", 19, 3, "DD 7E XX"),
"LD A,(IY+N)": Opcode("LD A,(IY+N)", 19, 3, "FD 7E XX"),
"LD A,(NN)": Opcode("LD A,(NN)", 13, 3, "3A XX XX"),
"LD A,A": Opcode("LD A,A", 4, 1, "7F"),
"LD A,C": Opcode("LD A,C", 4, 1, "79"),
"LD A,B": Opcode("LD A,B", 4, 1, "78"),
"LD A,E": Opcode("LD A,E", 4, 1, "7B"),
"LD A,D": Opcode("LD A,D", 4, 1, "7A"),
"LD A,H": Opcode("LD A,H", 4, 1, "7C"),
"LD A,L": Opcode("LD A,L", 4, 1, "7D"),
"LD A,I": Opcode("LD A,I", 9, 2, "ED 57"),
"LD A,N": Opcode("LD A,N", 7, 2, "3E XX"),
"LD A,R": Opcode("LD A,R", 4, 2, "ED 5F"),
"LD B,(HL)": Opcode("LD B,(HL)", 7, 1, "46"),
"LD B,(IX+N)": Opcode("LD B,(IX+N)", 19, 3, "DD 46 XX"),
"LD B,(IY+N)": Opcode("LD B,(IY+N)", 19, 3, "FD 46 XX"),
"LD B,A": Opcode("LD B,A", 4, 1, "47"),
"LD B,C": Opcode("LD B,C", 4, 1, "41"),
"LD B,B": Opcode("LD B,B", 4, 1, "40"),
"LD B,E": Opcode("LD B,E", 4, 1, "43"),
"LD B,D": Opcode("LD B,D", 4, 1, "42"),
"LD B,H": Opcode("LD B,H", 4, 1, "44"),
"LD B,L": Opcode("LD B,L", 4, 1, "45"),
"LD B,N": Opcode("LD B,N", 7, 2, "06 XX"),
"LD BC,(NN)": Opcode("LD BC,(NN)", 20, 4, "ED 4B XX XX"),
"LD BC,NN": Opcode("LD BC,NN", 10, 3, "01 XX XX"),
"LD C,(HL)": Opcode("LD C,(HL)", 7, 1, "4E"),
"LD C,(IX+N)": Opcode("LD C,(IX+N)", 19, 3, "DD 4E XX"),
"LD C,(IY+N)": Opcode("LD C,(IY+N)", 19, 3, "FD 4E XX"),
"LD C,A": Opcode("LD C,A", 4, 1, "4F"),
"LD C,C": Opcode("LD C,C", 4, 1, "49"),
"LD C,B": Opcode("LD C,B", 4, 1, "48"),
"LD C,E": Opcode("LD C,E", 4, 1, "4B"),
"LD C,D": Opcode("LD C,D", 4, 1, "4A"),
"LD C,H": Opcode("LD C,H", 4, 1, "4C"),
"LD C,L": Opcode("LD C,L", 4, 1, "4D"),
"LD C,N": Opcode("LD C,N", 7, 2, "0E XX"),
"LD D,(HL)": Opcode("LD D,(HL)", 7, 1, "56"),
"LD D,(IX+N)": Opcode("LD D,(IX+N)", 19, 3, "DD 56 XX"),
"LD D,(IY+N)": Opcode("LD D,(IY+N)", 19, 3, "FD 56 XX"),
"LD D,A": Opcode("LD D,A", 4, 1, "57"),
"LD D,C": Opcode("LD D,C", 4, 1, "51"),
"LD D,B": Opcode("LD D,B", 4, 1, "50"),
"LD D,E": Opcode("LD D,E", 4, 1, "53"),
"LD D,D": Opcode("LD D,D", 4, 1, "52"),
"LD D,H": Opcode("LD D,H", 4, 1, "54"),
"LD D,L": Opcode("LD D,L", 4, 1, "55"),
"LD D,N": Opcode("LD D,N", 7, 2, "16 XX"),
"LD DE,(NN)": Opcode("LD DE,(NN)", 20, 4, "ED 5B XX XX"),
"LD DE,NN": Opcode("LD DE,NN", 10, 3, "11 XX XX"),
"LD E,(HL)": Opcode("LD E,(HL)", 7, 1, "5E"),
"LD E,(IX+N)": Opcode("LD E,(IX+N)", 19, 3, "DD 5E XX"),
"LD E,(IY+N)": Opcode("LD E,(IY+N)", 19, 3, "FD 5E XX"),
"LD E,A": Opcode("LD E,A", 4, 1, "5F"),
"LD E,C": Opcode("LD E,C", 4, 1, "59"),
"LD E,B": Opcode("LD E,B", 4, 1, "58"),
"LD E,E": Opcode("LD E,E", 4, 1, "5B"),
"LD E,D": Opcode("LD E,D", 4, 1, "5A"),
"LD E,H": Opcode("LD E,H", 4, 1, "5C"),
"LD E,L": Opcode("LD E,L", 4, 1, "5D"),
"LD E,N": Opcode("LD E,N", 7, 2, "1E XX"),
"LD H,(HL)": Opcode("LD H,(HL)", 7, 1, "66"),
"LD H,(IX+N)": Opcode("LD H,(IX+N)", 19, 3, "DD 66 XX"),
"LD H,(IY+N)": Opcode("LD H,(IY+N)", 19, 3, "FD 66 XX"),
"LD H,A": Opcode("LD H,A", 4, 1, "67"),
"LD H,C": Opcode("LD H,C", 4, 1, "61"),
"LD H,B": Opcode("LD H,B", 4, 1, "60"),
"LD H,E": Opcode("LD H,E", 4, 1, "63"),
"LD H,D": Opcode("LD H,D", 4, 1, "62"),
"LD H,H": Opcode("LD H,H", 4, 1, "64"),
"LD H,L": Opcode("LD H,L", 4, 1, "65"),
"LD H,N": Opcode("LD H,N", 7, 2, "26 XX"),
"LD HL,(NN)": Opcode("LD HL,(NN)", 20, 3, "2A XX XX"),
"LD HL,NN": Opcode("LD HL,NN", 10, 3, "21 XX XX"),
"LD I,A": Opcode("LD I,A", 9, 2, "ED 47"),
"LD IX,(NN)": Opcode("LD IX,(NN)", 20, 4, "DD 2A XX XX"),
"LD IX,NN": Opcode("LD IX,NN", 14, 4, "DD 21 XX XX"),
"LD IY,(NN)": Opcode("LD IY,(NN)", 20, 4, "FD 2A XX XX"),
"LD IY,NN": Opcode("LD IY,NN", 14, 4, "FD 21 XX XX"),
"LD L,(HL)": Opcode("LD L,(HL)", 7, 1, "6E"),
"LD L,(IX+N)": Opcode("LD L,(IX+N)", 19, 3, "DD 6E XX"),
"LD L,(IY+N)": Opcode("LD L,(IY+N)", 19, 3, "FD 6E XX"),
"LD L,A": Opcode("LD L,A", 4, 1, "6F"),
"LD L,C": Opcode("LD L,C", 4, 1, "69"),
"LD L,B": Opcode("LD L,B", 4, 1, "68"),
"LD L,E": Opcode("LD L,E", 4, 1, "6B"),
"LD L,D": Opcode("LD L,D", 4, 1, "6A"),
"LD L,H": Opcode("LD L,H", 4, 1, "6C"),
"LD L,L": Opcode("LD L,L", 4, 1, "6D"),
"LD L,N": Opcode("LD L,N", 7, 2, "2E XX"),
"LD R,A": Opcode("LD R,A", 4, 2, "ED 4F"),
"LD SP,(NN)": Opcode("LD SP,(NN)", 20, 4, "ED 7B XX XX"),
"LD SP,HL": Opcode("LD SP,HL", 6, 1, "F9"),
"LD SP,IX": Opcode("LD SP,IX", 10, 2, "DD F9"),
"LD SP,IY": Opcode("LD SP,IY", 10, 2, "FD F9"),
"LD SP,NN": Opcode("LD SP,NN", 10, 3, "31 XX XX"),
"LDD": Opcode("LDD", 16, 2, "ED A8"),
"LDDR": Opcode("LDDR", 21, 2, "ED B8"),
"LDI": Opcode("LDI", 16, 2, "ED A0"),
"LDIR": Opcode("LDIR", 21, 2, "ED B0"),
"NEG": Opcode("NEG", 8, 2, "ED 44"),
"NOP": Opcode("NOP", 4, 1, "00"),
"OR (HL)": Opcode("OR (HL)", 7, 1, "B6"),
"OR (IX+N)": Opcode("OR (IX+N)", 19, 3, "DD B6 XX"),
"OR (IY+N)": Opcode("OR (IY+N)", 19, 3, "FD B6 XX"),
"OR A": Opcode("OR A", 4, 1, "B7"),
"OR C": Opcode("OR C", 4, 1, "B1"),
"OR B": Opcode("OR B", 4, 1, "B0"),
"OR E": Opcode("OR E", 4, 1, "B3"),
"OR D": Opcode("OR D", 4, 1, "B2"),
"OR H": Opcode("OR H", 4, 1, "B4"),
"OR L": Opcode("OR L", 4, 1, "B5"),
"OR N": Opcode("OR N", 7, 2, "F6 XX"),
"OTDR": Opcode("OTDR", 21, 2, "ED BB"),
"OTIR": Opcode("OTIR", 21, 2, "ED B3"),
"OUT (C),A": Opcode("OUT (C),A", 12, 2, "ED 79"),
"OUT (C),B": Opcode("OUT (C),B", 12, 2, "ED 41"),
"OUT (C),C": Opcode("OUT (C),C", 12, 2, "ED 49"),
"OUT (C),D": Opcode("OUT (C),D", 12, 2, "ED 51"),
"OUT (C),E": Opcode("OUT (C),E", 12, 2, "ED 59"),
"OUT (C),H": Opcode("OUT (C),H", 12, 2, "ED 61"),
"OUT (C),L": Opcode("OUT (C),L", 12, 2, "ED 69"),
"OUT (N),A": Opcode("OUT (N),A", 11, 2, "D3 XX"),
"OUTD": Opcode("OUTD", 16, 2, "ED AB"),
"OUTI": Opcode("OUTI", 16, 2, "ED A3"),
"POP AF": Opcode("POP AF", 10, 1, "F1"),
"POP BC": Opcode("POP BC", 10, 1, "C1"),
"POP DE": Opcode("POP DE", 10, 1, "D1"),
"POP HL": Opcode("POP HL", 10, 1, "E1"),
"POP IX": Opcode("POP IX", 14, 2, "DD E1"),
"POP IY": Opcode("POP IY", 14, 2, "FD E1"),
"PUSH AF": Opcode("PUSH AF", 11, 1, "F5"),
"PUSH BC": Opcode("PUSH BC", 11, 1, "C5"),
"PUSH DE": Opcode("PUSH DE", 11, 1, "D5"),
"PUSH HL": Opcode("PUSH HL", 11, 1, "E5"),
"PUSH IX": Opcode("PUSH IX", 15, 2, "DD E5"),
"PUSH IY": Opcode("PUSH IY", 15, 2, "FD E5"),
"RES 0,(HL)": Opcode("RES 0,(HL)", 15, 2, "CB 86"),
"RES 1,(HL)": Opcode("RES 1,(HL)", 15, 2, "CB 8E"),
"RES 2,(HL)": Opcode("RES 2,(HL)", 15, 2, "CB 96"),
"RES 3,(HL)": Opcode("RES 3,(HL)", 15, 2, "CB 9E"),
"RES 4,(HL)": Opcode("RES 4,(HL)", 15, 2, "CB A6"),
"RES 5,(HL)": Opcode("RES 5,(HL)", 15, 2, "CB AE"),
"RES 6,(HL)": Opcode("RES 6,(HL)", 15, 2, "CB B6"),
"RES 7,(HL)": Opcode("RES 7,(HL)", 15, 2, "CB BE"),
"RES 0,(IX+N)": Opcode("RES 0,(IX+N)", 23, 4, "DD CB XX 86"),
"RES 1,(IX+N)": Opcode("RES 1,(IX+N)", 23, 4, "DD CB XX 8E"),
"RES 2,(IX+N)": Opcode("RES 2,(IX+N)", 23, 4, "DD CB XX 96"),
"RES 3,(IX+N)": Opcode("RES 3,(IX+N)", 23, 4, "DD CB XX 9E"),
"RES 4,(IX+N)": Opcode("RES 4,(IX+N)", 23, 4, "DD CB XX A6"),
"RES 5,(IX+N)": Opcode("RES 5,(IX+N)", 23, 4, "DD CB XX AE"),
"RES 6,(IX+N)": Opcode("RES 6,(IX+N)", 23, 4, "DD CB XX B6"),
"RES 7,(IX+N)": Opcode("RES 7,(IX+N)", 23, 4, "DD CB XX BE"),
"RES 0,(IY+N)": Opcode("RES 0,(IY+N)", 23, 4, "FD CB XX 86"),
"RES 1,(IY+N)": Opcode("RES 1,(IY+N)", 23, 4, "FD CB XX 8E"),
"RES 2,(IY+N)": Opcode("RES 2,(IY+N)", 23, 4, "FD CB XX 96"),
"RES 3,(IY+N)": Opcode("RES 3,(IY+N)", 23, 4, "FD CB XX 9E"),
"RES 4,(IY+N)": Opcode("RES 4,(IY+N)", 23, 4, "FD CB XX A6"),
"RES 5,(IY+N)": Opcode("RES 5,(IY+N)", 23, 4, "FD CB XX AE"),
"RES 6,(IY+N)": Opcode("RES 6,(IY+N)", 23, 4, "FD CB XX B6"),
"RES 7,(IY+N)": Opcode("RES 7,(IY+N)", 23, 4, "FD CB XX BE"),
"RES 0,A": Opcode("RES 0,A", 8, 2, "CB 87"),
"RES 1,A": Opcode("RES 1,A", 8, 2, "CB 8F"),
"RES 2,A": Opcode("RES 2,A", 8, 2, "CB 97"),
"RES 3,A": Opcode("RES 3,A", 8, 2, "CB 9F"),
"RES 4,A": Opcode("RES 4,A", 8, 2, "CB A7"),
"RES 5,A": Opcode("RES 5,A", 8, 2, "CB AF"),
"RES 6,A": Opcode("RES 6,A", 8, 2, "CB B7"),
"RES 7,A": Opcode("RES 7,A", 8, 2, "CB BF"),
"RES 0,C": Opcode("RES 0,C", 8, 2, "CB 81"),
"RES 1,C": Opcode("RES 1,C", 8, 2, "CB 89"),
"RES 2,C": Opcode("RES 2,C", 8, 2, "CB 91"),
"RES 3,C": Opcode("RES 3,C", 8, 2, "CB 99"),
"RES 4,C": Opcode("RES 4,C", 8, 2, "CB A1"),
"RES 5,C": Opcode("RES 5,C", 8, 2, "CB A9"),
"RES 6,C": Opcode("RES 6,C", 8, 2, "CB B1"),
"RES 7,C": Opcode("RES 7,C", 8, 2, "CB B9"),
"RES 0,B": Opcode("RES 0,B", 8, 2, "CB 80"),
"RES 1,B": Opcode("RES 1,B", 8, 2, "CB 88"),
"RES 2,B": Opcode("RES 2,B", 8, 2, "CB 90"),
"RES 3,B": Opcode("RES 3,B", 8, 2, "CB 98"),
"RES 4,B": Opcode("RES 4,B", 8, 2, "CB A0"),
"RES 5,B": Opcode("RES 5,B", 8, 2, "CB A8"),
"RES 6,B": Opcode("RES 6,B", 8, 2, "CB B0"),
"RES 7,B": Opcode("RES 7,B", 8, 2, "CB B8"),
"RES 0,E": Opcode("RES 0,E", 8, 2, "CB 83"),
"RES 1,E": Opcode("RES 1,E", 8, 2, "CB 8B"),
"RES 2,E": Opcode("RES 2,E", 8, 2, "CB 93"),
"RES 3,E": Opcode("RES 3,E", 8, 2, "CB 9B"),
"RES 4,E": Opcode("RES 4,E", 8, 2, "CB A3"),
"RES 5,E": Opcode("RES 5,E", 8, 2, "CB AB"),
"RES 6,E": Opcode("RES 6,E", 8, 2, "CB B3"),
"RES 7,E": Opcode("RES 7,E", 8, 2, "CB BB"),
"RES 0,D": Opcode("RES 0,D", 8, 2, "CB 82"),
"RES 1,D": Opcode("RES 1,D", 8, 2, "CB 8A"),
"RES 2,D": Opcode("RES 2,D", 8, 2, "CB 92"),
"RES 3,D": Opcode("RES 3,D", 8, 2, "CB 9A"),
"RES 4,D": Opcode("RES 4,D", 8, 2, "CB A2"),
"RES 5,D": Opcode("RES 5,D", 8, 2, "CB AA"),
"RES 6,D": Opcode("RES 6,D", 8, 2, "CB B2"),
"RES 7,D": Opcode("RES 7,D", 8, 2, "CB BA"),
"RES 0,H": Opcode("RES 0,H", 8, 2, "CB 84"),
"RES 1,H": Opcode("RES 1,H", 8, 2, "CB 8C"),
"RES 2,H": Opcode("RES 2,H", 8, 2, "CB 94"),
"RES 3,H": Opcode("RES 3,H", 8, 2, "CB 9C"),
"RES 4,H": Opcode("RES 4,H", 8, 2, "CB A4"),
"RES 5,H": Opcode("RES 5,H", 8, 2, "CB AC"),
"RES 6,H": Opcode("RES 6,H", 8, 2, "CB B4"),
"RES 7,H": Opcode("RES 7,H", 8, 2, "CB BC"),
"RES 0,L": Opcode("RES 0,L", 8, 2, "CB 85"),
"RES 1,L": Opcode("RES 1,L", 8, 2, "CB 8D"),
"RES 2,L": Opcode("RES 2,L", 8, 2, "CB 95"),
"RES 3,L": Opcode("RES 3,L", 8, 2, "CB 9D"),
"RES 4,L": Opcode("RES 4,L", 8, 2, "CB A5"),
"RES 5,L": Opcode("RES 5,L", 8, 2, "CB AD"),
"RES 6,L": Opcode("RES 6,L", 8, 2, "CB B5"),
"RES 7,L": Opcode("RES 7,L", 8, 2, "CB BD"),
"RET": Opcode("RET", 10, 1, "C9"),
"RET C": Opcode("RET C", 11, 1, "D8"),
"RET M": Opcode("RET M", 11, 1, "F8"),
"RET NC": Opcode("RET NC", 11, 1, "D0"),
"RET NZ": Opcode("RET NZ", 11, 1, "C0"),
"RET P": Opcode("RET P", 11, 1, "F0"),
"RET PE": Opcode("RET PE", 11, 1, "E8"),
"RET PO": Opcode("RET PO", 11, 1, "E0"),
"RET Z": Opcode("RET Z", 11, 1, "C8"),
"RETI": Opcode("RETI", 14, 2, "ED 4D"),
"RETN": Opcode("RETN", 14, 2, "ED 45"),
"RL (HL)": Opcode("RL (HL)", 15, 2, "CB 16"),
"RL A": Opcode("RL A", 8, 2, "CB 17"),
"RL C": Opcode("RL C", 8, 2, "CB 11"),
"RL B": Opcode("RL B", 8, 2, "CB 10"),
"RL E": Opcode("RL E", 8, 2, "CB 13"),
"RL D": Opcode("RL D", 8, 2, "CB 12"),
"RL H": Opcode("RL H", 8, 2, "CB 14"),
"RL L": Opcode("RL L", 8, 2, "CB 15"),
"RL (IX+N)": Opcode("RL (IX+N)", 23, 4, "DD CB XX 16"),
"RL (IY+N)": Opcode("RL (IY+N)", 23, 4, "FD CB XX 16"),
"RLA": Opcode("RLA", 4, 1, "17"),
"RLC (HL)": Opcode("RLC (HL)", 15, 2, "CB 06"),
"RLC (IX+N)": Opcode("RLC (IX+N)", 23, 4, "DD CB XX 06"),
"RLC (IY+N)": Opcode("RLC (IY+N)", 23, 4, "FD CB XX 06"),
"RLC A": Opcode("RLC A", 8, 2, "CB 07"),
"RLC C": Opcode("RLC C", 8, 2, "CB 01"),
"RLC B": Opcode("RLC B", 8, 2, "CB 00"),
"RLC E": Opcode("RLC E", 8, 2, "CB 03"),
"RLC D": Opcode("RLC D", 8, 2, "CB 02"),
"RLC H": Opcode("RLC H", 8, 2, "CB 04"),
"RLC L": Opcode("RLC L", 8, 2, "CB 05"),
"RLCA": Opcode("RLCA", 4, 1, "07"),
"RLD": Opcode("RLD", 18, 2, "ED 6F"),
"RR (HL)": Opcode("RR (HL)", 15, 2, "CB 1E"),
"RR A": Opcode("RR A", 8, 2, "CB 1F"),
"RR C": Opcode("RR C", 8, 2, "CB 19"),
"RR B": Opcode("RR B", 8, 2, "CB 18"),
"RR E": Opcode("RR E", 8, 2, "CB 1B"),
"RR D": Opcode("RR D", 8, 2, "CB 1A"),
"RR H": Opcode("RR H", 8, 2, "CB 1C"),
"RR L": Opcode("RR L", 8, 2, "CB 1D"),
"RR (IX+N)": Opcode("RR (IX+N)", 23, 4, "DD CB XX 1E"),
"RR (IY+N)": Opcode("RR (IY+N)", 23, 4, "FD CB XX 1E"),
"RRA": Opcode("RRA", 4, 1, "1F"),
"RRC (HL)": Opcode("RRC (HL)", 15, 2, "CB 0E"),
"RRC (IX+N)": Opcode("RRC (IX+N)", 23, 4, "DD CB XX 0E"),
"RRC (IY+N)": Opcode("RRC (IY+N)", 23, 4, "FD CB XX 0E"),
"RRC A": Opcode("RRC A", 8, 2, "CB 0F"),
"RRC C": Opcode("RRC C", 8, 2, "CB 09"),
"RRC B": Opcode("RRC B", 8, 2, "CB 08"),
"RRC E": Opcode("RRC E", 8, 2, "CB 0B"),
"RRC D": Opcode("RRC D", 8, 2, "CB 0A"),
"RRC H": Opcode("RRC H", 8, 2, "CB 0C"),
"RRC L": Opcode("RRC L", 8, 2, "CB 0D"),
"RRCA": Opcode("RRCA", 4, 1, "0F"),
"RRD": Opcode("RRD", 18, 2, "ED 67"),
"RST 0H": Opcode("RST 0H", 11, 1, "C7"),
"RST 8H": Opcode("RST 8H", 11, 1, "CF"),
"RST 10H": Opcode("RST 10H", 11, 1, "D7"),
"RST 18H": Opcode("RST 18H", 11, 1, "DF"),
"RST 20H": Opcode("RST 20H", 11, 1, "E7"),
"RST 28H": Opcode("RST 28H", 11, 1, "EF"),
"RST 30H": Opcode("RST 30H", 11, 1, "F7"),
"RST 38H": Opcode("RST 38H", 11, 1, "FF"),
"SBC A,(HL)": Opcode("SBC (HL)", 7, 1, "9E"),
"SBC A,(IX+N)": Opcode("SBC A,(IX+N)", 19, 3, "DD 9E XX"),
"SBC A,(IY+N)": Opcode("SBC A,(IY+N)", 19, 3, "FD 9E XX"),
"SBC A,N": Opcode("SBC A,N", 7, 2, "DE XX"),
"SBC A,A": Opcode("SBC A,A", 4, 1, "9F"),
"SBC A,B": Opcode("SBC A,B", 4, 1, "98"),
"SBC A,C": Opcode("SBC A,C", 4, 1, "99"),
"SBC A,D": Opcode("SBC A,D", 4, 1, "9A"),
"SBC A,E": Opcode("SBC A,E", 4, 1, "9B"),
"SBC A,H": Opcode("SBC A,H", 4, 1, "9C"),
"SBC A,L": Opcode("SBC A,L", 4, 1, "9D"),
"SBC HL,BC": Opcode("SBC HL,BC", 15, 2, "ED 42"),
"SBC HL,DE": Opcode("SBC HL,DE", 15, 2, "ED 52"),
"SBC HL,HL": Opcode("SBC HL,HL", 15, 2, "ED 62"),
"SBC HL,SP": Opcode("SBC HL,SP", 15, 2, "ED 72"),
"SCF": Opcode("SCF", 4, 1, "37"),
"SET 0,(HL)": Opcode("SET 0,(HL)", 15, 2, "CB C6"),
"SET 1,(HL)": Opcode("SET 1,(HL)", 15, 2, "CB CE"),
"SET 2,(HL)": Opcode("SET 2,(HL)", 15, 2, "CB D6"),
"SET 3,(HL)": Opcode("SET 3,(HL)", 15, 2, "CB DE"),
"SET 4,(HL)": Opcode("SET 4,(HL)", 15, 2, "CB E6"),
"SET 5,(HL)": Opcode("SET 5,(HL)", 15, 2, "CB EE"),
"SET 6,(HL)": Opcode("SET 6,(HL)", 15, 2, "CB F6"),
"SET 7,(HL)": Opcode("SET 7,(HL)", 15, 2, "CB FE"),
"SET 0,(IX+N)": Opcode("SET 0,(IX+N)", 23, 4, "DD CB XX C6"),
"SET 1,(IX+N)": Opcode("SET 1,(IX+N)", 23, 4, "DD CB XX CE"),
"SET 2,(IX+N)": Opcode("SET 2,(IX+N)", 23, 4, "DD CB XX D6"),
"SET 3,(IX+N)": Opcode("SET 3,(IX+N)", 23, 4, "DD CB XX DE"),
"SET 4,(IX+N)": Opcode("SET 4,(IX+N)", 23, 4, "DD CB XX E6"),
"SET 5,(IX+N)": Opcode("SET 5,(IX+N)", 23, 4, "DD CB XX EE"),
"SET 6,(IX+N)": Opcode("SET 6,(IX+N)", 23, 4, "DD CB XX F6"),
"SET 7,(IX+N)": Opcode("SET 7,(IX+N)", 23, 4, "DD CB XX FE"),
"SET 0,(IY+N)": Opcode("SET 0,(IY+N)", 23, 4, "FD CB XX C6"),
"SET 1,(IY+N)": Opcode("SET 1,(IY+N)", 23, 4, "FD CB XX CE"),
"SET 2,(IY+N)": Opcode("SET 2,(IY+N)", 23, 4, "FD CB XX D6"),
"SET 3,(IY+N)": Opcode("SET 3,(IY+N)", 23, 4, "FD CB XX DE"),
"SET 4,(IY+N)": Opcode("SET 4,(IY+N)", 23, 4, "FD CB XX E6"),
"SET 5,(IY+N)": Opcode("SET 5,(IY+N)", 23, 4, "FD CB XX EE"),
"SET 6,(IY+N)": Opcode("SET 6,(IY+N)", 23, 4, "FD CB XX F6"),
"SET 7,(IY+N)": Opcode("SET 7,(IY+N)", 23, 4, "FD CB XX FE"),
"SET 0,A": Opcode("SET 0,A", 8, 2, "CB C7"),
"SET 1,A": Opcode("SET 1,A", 8, 2, "CB CF"),
"SET 2,A": Opcode("SET 2,A", 8, 2, "CB D7"),
"SET 3,A": Opcode("SET 3,A", 8, 2, "CB DF"),
"SET 4,A": Opcode("SET 4,A", 8, 2, "CB E7"),
"SET 5,A": Opcode("SET 5,A", 8, 2, "CB EF"),
"SET 6,A": Opcode("SET 6,A", 8, 2, "CB F7"),
"SET 7,A": Opcode("SET 7,A", 8, 2, "CB FF"),
"SET 0,C": Opcode("SET 0,C", 8, 2, "CB C1"),
"SET 1,C": Opcode("SET 1,C", 8, 2, "CB C9"),
"SET 2,C": Opcode("SET 2,C", 8, 2, "CB D1"),
"SET 3,C": Opcode("SET 3,C", 8, 2, "CB D9"),
"SET 4,C": Opcode("SET 4,C", 8, 2, "CB E1"),
"SET 5,C": Opcode("SET 5,C", 8, 2, "CB E9"),
"SET 6,C": Opcode("SET 6,C", 8, 2, "CB F1"),
"SET 7,C": Opcode("SET 7,C", 8, 2, "CB F9"),
"SET 0,B": Opcode("SET 0,B", 8, 2, "CB C0"),
"SET 1,B": Opcode("SET 1,B", 8, 2, "CB C8"),
"SET 2,B": Opcode("SET 2,B", 8, 2, "CB D0"),
"SET 3,B": Opcode("SET 3,B", 8, 2, "CB D8"),
"SET 4,B": Opcode("SET 4,B", 8, 2, "CB E0"),
"SET 5,B": Opcode("SET 5,B", 8, 2, "CB E8"),
"SET 6,B": Opcode("SET 6,B", 8, 2, "CB F0"),
"SET 7,B": Opcode("SET 7,B", 8, 2, "CB F8"),
"SET 0,E": Opcode("SET 0,E", 8, 2, "CB C3"),
"SET 1,E": Opcode("SET 1,E", 8, 2, "CB CB"),
"SET 2,E": Opcode("SET 2,E", 8, 2, "CB D3"),
"SET 3,E": Opcode("SET 3,E", 8, 2, "CB DB"),
"SET 4,E": Opcode("SET 4,E", 8, 2, "CB E3"),
"SET 5,E": Opcode("SET 5,E", 8, 2, "CB EB"),
"SET 6,E": Opcode("SET 6,E", 8, 2, "CB F3"),
"SET 7,E": Opcode("SET 7,E", 8, 2, "CB FB"),
"SET 0,D": Opcode("SET 0,D", 8, 2, "CB C2"),
"SET 1,D": Opcode("SET 1,D", 8, 2, "CB CA"),
"SET 2,D": Opcode("SET 2,D", 8, 2, "CB D2"),
"SET 3,D": Opcode("SET 3,D", 8, 2, "CB DA"),
"SET 4,D": Opcode("SET 4,D", 8, 2, "CB E2"),
"SET 5,D": Opcode("SET 5,D", 8, 2, "CB EA"),
"SET 6,D": Opcode("SET 6,D", 8, 2, "CB F2"),
"SET 7,D": Opcode("SET 7,D", 8, 2, "CB FA"),
"SET 0,H": Opcode("SET 0,H", 8, 2, "CB C4"),
"SET 1,H": Opcode("SET 1,H", 8, 2, "CB CC"),
"SET 2,H": Opcode("SET 2,H", 8, 2, "CB D4"),
"SET 3,H": Opcode("SET 3,H", 8, 2, "CB DC"),
"SET 4,H": Opcode("SET 4,H", 8, 2, "CB E4"),
"SET 5,H": Opcode("SET 5,H", 8, 2, "CB EC"),
"SET 6,H": Opcode("SET 6,H", 8, 2, "CB F4"),
"SET 7,H": Opcode("SET 7,H", 8, 2, "CB FC"),
"SET 0,L": Opcode("SET 0,L", 8, 2, "CB C5"),
"SET 1,L": Opcode("SET 1,L", 8, 2, "CB CD"),
"SET 2,L": Opcode("SET 2,L", 8, 2, "CB D5"),
"SET 3,L": Opcode("SET 3,L", 8, 2, "CB DD"),
"SET 4,L": Opcode("SET 4,L", 8, 2, "CB E5"),
"SET 5,L": Opcode("SET 5,L", 8, 2, "CB ED"),
"SET 6,L": Opcode("SET 6,L", 8, 2, "CB F5"),
"SET 7,L": Opcode("SET 7,L", 8, 2, "CB FD"),
"SLA (HL)": Opcode("SLA (HL)", 15, 2, "CB 26"),
"SLA (IX+N)": Opcode("SLA (IX+N)", 23, 4, "DD CB XX 26"),
"SLA (IY+N)": Opcode("SLA (IY+N)", 23, 4, "FD CB XX 26"),
"SLA A": Opcode("SLA A", 8, 2, "CB 27"),
"SLA C": Opcode("SLA C", 8, 2, "CB 21"),
"SLA B": Opcode("SLA B", 8, 2, "CB 20"),
"SLA E": Opcode("SLA E", 8, 2, "CB 23"),
"SLA D": Opcode("SLA D", 8, 2, "CB 22"),
"SLA H": Opcode("SLA H", 8, 2, "CB 24"),
"SLA L": Opcode("SLA L", 8, 2, "CB 25"),
"SRA (HL)": Opcode("SRA (HL)", 15, 2, "CB 2E"),
"SRA (IX+N)": Opcode("SRA (IX+N)", 23, 4, "DD CB XX 2E"),
"SRA (IY+N)": Opcode("SRA (IY+N)", 23, 4, "FD CB XX 2E"),
"SRA A": Opcode("SRA A", 8, 2, "CB 2F"),
"SRA C": Opcode("SRA C", 8, 2, "CB 29"),
"SRA B": Opcode("SRA B", 8, 2, "CB 28"),
"SRA E": Opcode("SRA E", 8, 2, "CB 2B"),
"SRA D": Opcode("SRA D", 8, 2, "CB 2A"),
"SRA H": Opcode("SRA H", 8, 2, "CB 2C"),
"SRA L": Opcode("SRA L", 8, 2, "CB 2D"),
"SRL (HL)": Opcode("SRL (HL)", 15, 2, "CB 3E"),
"SRL (IX+N)": Opcode("SRL (IX+N)", 23, 4, "DD CB XX 3E"),
"SRL (IY+N)": Opcode("SRL (IY+N)", 23, 4, "FD CB XX 3E"),
"SRL A": Opcode("SRL A", 8, 2, "CB 3F"),
"SRL C": Opcode("SRL C", 8, 2, "CB 39"),
"SRL B": Opcode("SRL B", 8, 2, "CB 38"),
"SRL E": Opcode("SRL E", 8, 2, "CB 3B"),
"SRL D": Opcode("SRL D", 8, 2, "CB 3A"),
"SRL H": Opcode("SRL H", 8, 2, "CB 3C"),
"SRL L": Opcode("SRL L", 8, 2, "CB 3D"),
"SUB (HL)": Opcode("SUB (HL)", 7, 1, "96"),
"SUB (IX+N)": Opcode("SUB (IX+N)", 19, 3, "DD 96 XX"),
"SUB (IY+N)": Opcode("SUB (IY+N)", 19, 3, "FD 96 XX"),
"SUB A": Opcode("SUB A", 4, 1, "97"),
"SUB C": Opcode("SUB C", 4, 1, "91"),
"SUB B": Opcode("SUB B", 4, 1, "90"),
"SUB E": Opcode("SUB E", 4, 1, "93"),
"SUB D": Opcode("SUB D", 4, 1, "92"),
"SUB H": Opcode("SUB H", 4, 1, "94"),
"SUB L": Opcode("SUB L", 4, 1, "95"),
"SUB N": Opcode("SUB N", 7, 2, "D6 XX"),
"XOR (HL)": Opcode("XOR (HL)", 7, 1, "AE"),
"XOR (IX+N)": Opcode("XOR (IX+N)", 19, 3, "DD AE XX"),
"XOR (IY+N)": Opcode("XOR (IY+N)", 19, 3, "FD AE XX"),
"XOR A": Opcode("XOR A", 4, 1, "AF"),
"XOR C": Opcode("XOR C", 4, 1, "A9"),
"XOR B": Opcode("XOR B", 4, 1, "A8"),
"XOR E": Opcode("XOR E", 4, 1, "AB"),
"XOR D": Opcode("XOR D", 4, 1, "AA"),
"XOR H": Opcode("XOR H", 4, 1, "AC"),
"XOR L": Opcode("XOR L", 4, 1, "AD"),
"XOR N": Opcode("XOR N", 7, 2, "EE XX"),
# Undocumented opcodes
"SLL A": Opcode("SLL A", 8, 2, "CB 37"),
"SLL C": Opcode("SLL C", 8, 2, "CB 31"),
"SLL B": Opcode("SLL B", 8, 2, "CB 30"),
"SLL E": Opcode("SLL E", 8, 2, "CB 33"),
"SLL D": Opcode("SLL D", 8, 2, "CB 32"),
"SLL H": Opcode("SLL H", 8, 2, "CB 34"),
"SLL L": Opcode("SLL L", 8, 2, "CB 35"),
"SLL (HL)": Opcode("SLL (HL)", 15, 2, "CB 36"),
"SLL (IX+N)": Opcode("SLL (IX+N)", 19, 4, "DD CB XX 36"),
"SLL (IY+N)": Opcode("SLL (IY+N)", 19, 4, "FD CB XX 36"),
"INC IXH": Opcode("INC IXH", 8, 2, "DD 24"),
"DEC IXH": Opcode("DEC IXH", 8, 2, "DD 25"),
"INC IXL": Opcode("INC IXL", 8, 2, "DD 2C"),
"DEC IXL": Opcode("DEC IXL", 8, 2, "DD 2D"),
"INC IYH": Opcode("INC IYH", 8, 2, "FD 24"),
"DEC IYH": Opcode("DEC IYH", 8, 2, "FD 25"),
"INC IYL": Opcode("INC IYL", 8, 2, "FD 2C"),
"DEC IYL": Opcode("DEC IYL", 8, 2, "FD 2D"),
"LD IXH,N": Opcode("LD IXH,N", 12, 3, "DD 26 XX"),
"LD IXL,N": Opcode("LD IXL,N", 12, 3, "DD 2E XX"),
"LD IYH,N": Opcode("LD IYH,N", 12, 3, "FD 26 XX"),
"LD IYL,N": Opcode("LD IYL,N", 12, 3, "FD 2E XX"),
"LD A,IXH": Opcode("LD A,IXH", 8, 2, "DD 7C"),
"LD A,IXL": Opcode("LD A,IXL", 8, 2, "DD 7D"),
"LD B,IXH": Opcode("LD B,IXH", 8, 2, "DD 44"),
"LD B,IXL": Opcode("LD B,IXL", 8, 2, "DD 45"),
"LD C,IXH": Opcode("LD C,IXH", 8, 2, "DD 4C"),
"LD C,IXL": Opcode("LD C,IXL", 8, 2, "DD 4D"),
"LD D,IXH": Opcode("LD D,IXH", 8, 2, "DD 54"),
"LD D,IXL": Opcode("LD D,IXL", 8, 2, "DD 55"),
"LD E,IXH": Opcode("LD E,IXH", 8, 2, "DD 5C"),
"LD E,IXL": Opcode("LD E,IXL", 8, 2, "DD 5D"),
"LD A,IYH": Opcode("LD A,IYH", 8, 2, "FD 7C"),
"LD A,IYL": Opcode("LD A,IYL", 8, 2, "FD 7D"),
"LD B,IYH": Opcode("LD B,IYH", 8, 2, "FD 44"),
"LD B,IYL": Opcode("LD B,IYL", 8, 2, "FD 45"),
"LD C,IYH": Opcode("LD C,IYH", 8, 2, "FD 4C"),
"LD C,IYL": Opcode("LD C,IYL", 8, 2, "FD 4D"),
"LD D,IYH": Opcode("LD D,IYH", 8, 2, "FD 54"),
"LD D,IYL": Opcode("LD D,IYL", 8, 2, "FD 55"),
"LD E,IYH": Opcode("LD E,IYH", 8, 2, "FD 5C"),
"LD E,IYL": Opcode("LD E,IYL", 8, 2, "FD 5D"),
"LD IXH,B": Opcode("LD IXH,B", 8, 2, "DD 60"),
"LD IXH,C": Opcode("LD IXH,C", 8, 2, "DD 61"),
"LD IXH,D": Opcode("LD IXH,D", 8, 2, "DD 62"),
"LD IXH,E": Opcode("LD IXH,E", 8, 2, "DD 63"),
"LD IXH,IXH": Opcode("LD IXH,IXH", 8, 2, "DD 64"),
"LD IXH,IXL": Opcode("LD IXH,IXL", 8, 2, "DD 65"),
"LD IXH,A": Opcode("LD IXH,A", 8, 2, "DD 67"),
"LD IXL,B": Opcode("LD IXL,B", 8, 2, "DD 68"),
"LD IXL,C": Opcode("LD IXL,C", 8, 2, "DD 69"),
"LD IXL,D": Opcode("LD IXL,D", 8, 2, "DD 6A"),
"LD IXL,E": Opcode("LD IXL,E", 8, 2, "DD 6B"),
"LD IXL,IXH": Opcode("LD IXL,IXH", 8, 2, "DD 6C"),
"LD IXL,IXL": Opcode("LD IXL,IXL", 8, 2, "DD 6D"),
"LD IXL,A": Opcode("LD IXL,A", 8, 2, "DD 6F"),
"LD IYH,B": Opcode("LD IYH,B", 8, 2, "FD 60"),
"LD IYH,C": Opcode("LD IYH,C", 8, 2, "FD 61"),
"LD IYH,D": Opcode("LD IYH,D", 8, 2, "FD 62"),
"LD IYH,E": Opcode("LD IYH,E", 8, 2, "FD 63"),
"LD IYH,IYH": Opcode("LD IYH,IYH", 8, 2, "DD 64"),
"LD IYH,IYL": Opcode("LD IYH,IYL", 8, 2, "DD 65"),
"LD IYH,A": Opcode("LD IYH,A", 8, 2, "FD 67"),
"LD IYL,B": Opcode("LD IYL,B", 8, 2, "FD 68"),
"LD IYL,C": Opcode("LD IYL,C", 8, 2, "FD 69"),
"LD IYL,D": Opcode("LD IYL,D", 8, 2, "FD 6A"),
"LD IYL,E": Opcode("LD IYL,E", 8, 2, "FD 6B"),
"LD IYL,IYH": Opcode("LD IYL,IYH", 8, 2, "FD 6C"),
"LD IYL,IYL": Opcode("LD IYL,IYL", 8, 2, "FD 6D"),
"LD IYL,A": Opcode("LD IYL,A", 8, 2, "FD 6F"),
"ADD A,IXH": Opcode("ADD A,IXH", 8, 2, "DD 84"),
"ADD A,IXL": Opcode("ADD A,IXL", 8, 2, "DD 85"),
"ADC A,IXH": Opcode("ADC A,IXH", 8, 2, "DD 8C"),
"ADC A,IXL": Opcode("ADC A,IXL", 8, 2, "DD 8D"),
"ADD A,IYH": Opcode("ADD A,IYH", 8, 2, "FD 84"),
"ADD A,IYL": Opcode("ADD A,IYL", 8, 2, "FD 85"),
"ADC A,IYH": Opcode("ADC A,IYH", 8, 2, "FD 8C"),
"ADC A,IYL": Opcode("ADC A,IYL", 8, 2, "FD 8D"),
"SUB IXH": Opcode("SUB IXH", 8, 2, "DD 94"),
"SUB IXL": Opcode("SUB IXL", 8, 2, "DD 95"),
"SBC A,IXH": Opcode("SBC A,IXH", 8, 2, "DD 9C"),
"SBC A,IXL": Opcode("SBC A,IXL", 8, 2, "DD 9D"),
"SUB IYH": Opcode("SUB IYH", 8, 2, "FD 94"),
"SUB IYL": Opcode("SUB IYL", 8, 2, "FD 95"),
"SBC A,IYH": Opcode("SBC A,IYH", 8, 2, "FD 9C"),
"SBC A,IYL": Opcode("SBC A,IYL", 8, 2, "FD 9D"),
"AND IXH": Opcode("AND IXH", 8, 2, "DD A4"),
"AND IXL": Opcode("AND IXL", 8, 2, "DD A5"),
"AND IYH": Opcode("AND IYH", 8, 2, "FD A4"),
"AND IYL": Opcode("AND IYL", 8, 2, "FD A5"),
"XOR IXH": Opcode("XOR IXH", 8, 2, "DD AC"),
"XOR IXL": Opcode("XOR IXL", 8, 2, "DD AD"),
"XOR IYH": Opcode("XOR IYH", 8, 2, "FD AC"),
"XOR IYL": Opcode("XOR IYL", 8, 2, "FD AD"),
"OR IXH": Opcode("OR IXH", 8, 2, "DD B4"),
"OR IXL": Opcode("OR IXL", 8, 2, "DD B5"),
"OR IYH": Opcode("OR IYH", 8, 2, "FD B4"),
"OR IYL": Opcode("OR IYL", 8, 2, "FD B5"),
"CP IXH": Opcode("CP IXH", 8, 2, "DD BC"),
"CP IXL": Opcode("CP IXL", 8, 2, "DD BD"),
"CP IYH": Opcode("CP IYH", 8, 2, "FD BC"),
"CP IYL": Opcode("CP IYL", 8, 2, "FD BD"),
# ZX NEXT extra opcodes
"LDIX": Opcode("LDIX", 16, 2, "ED A4"),
"LDWS": Opcode("LDWS", 14, 2, "ED A5"),
"LDIRX": Opcode("LDIRX", 21, 2, "ED B4"),
"LDDX": Opcode("LDDX", 16, 2, "ED AC"),
"LDDRX": Opcode("LDDRX", 21, 2, "ED BC"),
"LDPIRX": Opcode("LDPIRX", 21, 2, "ED B7"),
"OUTINB": Opcode("OUTINB", 16, 2, "ED 90"),
"MUL D,E": Opcode("MUL D,E", 8, 2, "ED 30"),
"ADD HL,A": Opcode("ADD HL,A", 8, 2, "ED 31"),
"ADD DE,A": Opcode("ADD DE,A", 8, 2, "ED 32"),
"ADD BC,A": Opcode("ADD BC,A", 8, 2, "ED 33"),
"ADD HL,NN": Opcode("ADD HL,NN", 16, 4, "ED 34 XX XX"),
"ADD DE,NN": Opcode("ADD DE,NN", 16, 4, "ED 35 XX XX"),
"ADD BC,NN": Opcode("ADD BC,NN", 16, 4, "ED 36 XX XX"),
"SWAPNIB": Opcode("SWAPNIB", 8, 2, "ED 23"),
"MIRROR": Opcode("MIRROR", 8, 2, "ED 24"),
"PUSH NN": Opcode("PUSH NN", 23, 4, "ED 8A XX XX"),
"NEXTREG N,N": Opcode("NEXTREG N,N", 20, 4, "ED 91 XX XX"),
"NEXTREG N,A": Opcode("NEXTREG N,A", 17, 3, "ED 92 XX"),
"PIXELDN": Opcode("PIXELDN", 8, 2, "ED 93"),
"PIXELAD": Opcode("PIXELAD", 8, 2, "ED 94"),
"SETAE": Opcode("SETAE", 8, 2, "ED 95"),
"TEST N": Opcode("TEST N", 11, 3, "ED 27 XX"),
"BSLA DE,B": Opcode("BSLA DE,B", 8, 2, "ED 28"),
"BSRA DE,B": Opcode("BSRA DE,B", 8, 2, "ED 29"),
"BSRL DE,B": Opcode("BSRL DE,B", 8, 2, "ED 2A"),
"BSRF DE,B": Opcode("BSRF DE,B", 8, 2, "ED 2B"),
"BRLC DE,B": Opcode("BRLC DE,B", 8, 2, "ED 2C"),
"JP (C)": Opcode("JP (C)", 13, 2, "ED 98"),
}
# Z80 asm instruction list
Z80INSTR = set(x.split()[0] for x in Z80SET)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/libzxbasm/z80.py
|
z80.py
|
This directory contains a library of "basic" BASIC functions.
Some of them are related to ZX Spectrum BASIC (i.e. ATTR) while
others are more standard to FREE BASIC (csrlin or pos)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/library/README
|
README
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
from . import zx48k
__all__ = [
'zx48k',
]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/__init__.py
|
__init__.py
|
# -*- coding: utf-8 -*-
from api.constants import TYPE
import symbols
from ast_ import NodeVisitor
from .backend import Quad, MEMORY
from api.debug import __DEBUG__
class TranslatorInstVisitor(NodeVisitor):
@staticmethod
def emit(*args):
""" Convert the given args to a Quad (3 address code) instruction
"""
quad = Quad(*args)
__DEBUG__('EMIT ' + str(quad))
MEMORY.append(quad)
@staticmethod
def TSUFFIX(type_):
assert isinstance(type_, symbols.TYPE) or TYPE.is_valid(type_)
_TSUFFIX = {TYPE.byte_: 'i8', TYPE.ubyte: 'u8',
TYPE.integer: 'i16', TYPE.uinteger: 'u16',
TYPE.long_: 'i32', TYPE.ulong: 'u32',
TYPE.fixed: 'f16', TYPE.float_: 'f',
TYPE.string: 'str'
}
if isinstance(type_, symbols.TYPEREF):
type_ = type_.final
assert isinstance(type_, symbols.BASICTYPE)
if isinstance(type_, symbols.BASICTYPE):
return _TSUFFIX[type_.type_]
return _TSUFFIX[type_]
def ic_aaddr(self, t1, t2):
return self.emit('aaddr', t1, t2)
def ic_abs(self, type_, t1, t2):
return self.emit('abs' + self.TSUFFIX(type_), t1, t2)
def ic_add(self, type_, t1, t2, t3):
return self.emit('add' + self.TSUFFIX(type_), t1, t2, t3)
def ic_aload(self, type_, t1, mangle: str):
return self.emit('aload' + self.TSUFFIX(type_), t1, mangle)
def ic_and(self, type_):
return self.emit('and' + self.TSUFFIX(type_))
def ic_astore(self, type_, addr: str, t):
return self.emit('astore' + self.TSUFFIX(type_), addr, t)
def ic_band(self, type_):
return self.emit('band' + self.TSUFFIX(type_))
def ic_bnot(self, type_, t1, t2):
return self.emit('bnot' + self.TSUFFIX(type_), t1, t2)
def ic_bor(self, type_):
return self.emit('bor' + self.TSUFFIX(type_))
def ic_bxor(self, type_):
return self.emit('bxor' + self.TSUFFIX(type_))
def ic_call(self, label: str, num: int):
return self.emit('call', label, num)
def ic_cast(self, t1, type1, type2, t2):
self.emit('cast', t1, self.TSUFFIX(type1), self.TSUFFIX(type2), t2)
def ic_data(self, type_, data: list):
return self.emit('data', self.TSUFFIX(type_), data)
def ic_deflabel(self, label: str, t):
return self.emit('deflabel', label, t)
def ic_div(self, type_):
return self.emit('div' + self.TSUFFIX(type_))
def ic_end(self, t):
return self.emit('end', t)
def ic_enter(self, arg):
return self.emit('enter', arg)
def ic_eq(self, type_, t, t1, t2):
return self.emit('eq' + self.TSUFFIX(type_), t, t1, t2)
def ic_exchg(self):
return self.emit('exchg')
def ic_fparam(self, type_, t):
return self.emit('fparam' + self.TSUFFIX(type_), t)
def ic_fpload(self, type_, t, offset):
return self.emit('fpload' + self.TSUFFIX(type_), t, offset)
def ic_ge(self, type_, t, t1, t2):
return self.emit('ge' + self.TSUFFIX(type_), t, t1, t2)
def ic_gt(self, type_, t, t1, t2):
return self.emit('gt' + self.TSUFFIX(type_), t, t1, t2)
def ic_in(self, t):
return self.emit('in', t)
def ic_inline(self, asm_code: str, t):
return self.emit('inline', asm_code, t)
def ic_jgezero(self, type_, t, label: str):
return self.emit('jgezero' + self.TSUFFIX(type_), t, label)
def ic_jnzero(self, type_, t, label: str):
return self.emit('jnzero' + self.TSUFFIX(type_), t, label)
def ic_jump(self, label: str):
return self.emit('jump', label)
def ic_jzero(self, type_, t, label: str):
return self.emit('jzero' + self.TSUFFIX(type_), t, label)
def ic_label(self, label: str):
return self.emit('label', label)
def ic_larrd(self, offset, arg1, size, arg2, bound_ptrs):
return self.emit('larrd', offset, arg1, size, arg2, bound_ptrs)
def ic_le(self, type_, t, t1, t2):
return self.emit('le' + self.TSUFFIX(type_), t, t1, t2)
def ic_leave(self, convention: str):
return self.emit('leave', convention)
def ic_lenstr(self, t1, t2):
return self.emit('lenstr', t1, t2)
def ic_load(self, type_, t1, t2):
return self.emit('load' + self.TSUFFIX(type_), t1, t2)
def ic_lt(self, type_, t, t1, t2):
return self.emit('lt' + self.TSUFFIX(type_), t, t1, t2)
def ic_lvard(self, offset, default_value: list):
return self.emit('lvard', offset, default_value)
def ic_lvarx(self, type_, offset, default_value: list):
self.emit('lvarx', offset, self.TSUFFIX(type_), default_value)
def ic_memcopy(self, t1, t2, t3):
return self.emit('memcopy', t1, t2, t3)
def ic_mod(self, type_):
return self.emit('mod' + self.TSUFFIX(type_))
def ic_mul(self, type_):
return self.emit('mul' + self.TSUFFIX(type_))
def ic_ne(self, type_, t, t1, t2):
return self.emit('ne' + self.TSUFFIX(type_), t, t1, t2)
def ic_neg(self, type_, t1, t2):
return self.emit('neg' + self.TSUFFIX(type_), t1, t2)
def ic_nop(self):
return self.emit('nop')
def ic_not(self, type_, t1, t2):
return self.emit('not' + self.TSUFFIX(type_), t1, t2)
def ic_or(self, type_):
return self.emit('or' + self.TSUFFIX(type_))
def ic_org(self, type_):
return self.emit('org' + self.TSUFFIX(type_))
def ic_out(self, t1, t2):
return self.emit('out', t1, t2)
def ic_paaddr(self, t1, t2):
return self.emit('paaddr', t1, t2)
def ic_paddr(self, t1, t2):
return self.emit('paddr', t1, t2)
def ic_paload(self, type_, t, offset: int):
return self.emit('paload' + self.TSUFFIX(type_), t, offset)
def ic_param(self, type_, t):
return self.emit('param' + self.TSUFFIX(type_), t)
def ic_pastore(self, type_, offset, t):
return self.emit('pastore' + self.TSUFFIX(type_), offset, t)
def ic_pload(self, type_, t1, offset):
return self.emit('pload' + self.TSUFFIX(type_), t1, offset)
def ic_pow(self, type_):
return self.emit('pow' + self.TSUFFIX(type_))
def ic_pstore(self, type_, offset, t):
return self.emit('pstore' + self.TSUFFIX(type_), offset, t)
def ic_ret(self, type_, t, addr):
return self.emit('ret' + self.TSUFFIX(type_), t, addr)
def ic_return(self, addr):
return self.emit('ret', addr)
def ic_shl(self, type_):
return self.emit('shl' + self.TSUFFIX(type_))
def ic_shr(self, type_):
return self.emit('shr' + self.TSUFFIX(type_))
def ic_store(self, type_, t1, t2):
return self.emit('store' + self.TSUFFIX(type_), t1, t2)
def ic_sub(self, type_):
return self.emit('sub' + self.TSUFFIX(type_))
def ic_var(self, name: str, size_):
return self.emit('var', name, size_)
def ic_vard(self, name: str, data: list):
return self.emit('vard', name, data)
def ic_varx(self, name: str, type_, default_value: list):
return self.emit('varx', name, self.TSUFFIX(type_), default_value)
def ic_xor(self, type_):
return self.emit('xor' + self.TSUFFIX(type_))
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/translatorinstvisitor.py
|
translatorinstvisitor.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
__doc___ = """This library converts duration,pitch for a beep
from floating point to HL,DE Integers.
"""
class BeepError(BaseException):
"""Returned when invalid pitch specified (e.g. Out of Range)
"""
def __init__(self, msg='Invalid beep parameters'):
self.message = msg
def __str__(self):
return self.message
# Pitch (frequencies) tables
TABLE = [261.625565290, # C
277.182631135,
293.664768100,
311.126983881,
329.627557039,
349.228231549,
369.994422674,
391.995436072,
415.304697513,
440.000000000,
466.163761616,
493.883301378]
def getDEHL(duration, pitch):
"""Converts duration,pitch to a pair of unsigned 16 bit integers,
to be loaded in DE,HL, following the ROM listing.
Returns a t-uple with the DE, HL values.
"""
intPitch = int(pitch)
fractPitch = pitch - intPitch # Gets fractional part
tmp = 1 + 0.0577622606 * fractPitch
if not -60 <= intPitch <= 127:
raise BeepError('Pitch out of range: must be between [-60, 127]')
if duration < 0 or duration > 10:
raise BeepError('Invalid duration: must be between [0, 10]')
A = intPitch + 60
B = -5 + int(A / 12) # -5 <= B <= 10
A %= 0xC # Semitones above C
frec = TABLE[A]
tmp2 = tmp * frec
f = tmp2 * 2.0 ** B
DE = int(0.5 + f * duration - 1)
HL = int(0.5 + 437500.0 / f - 30.125)
return DE, HL
if __name__ == '__main__':
# Simple test
print(getDEHL(1, 0), [hex(x) for x in getDEHL(1, 0)])
print(getDEHL(5, 0), [hex(x) for x in getDEHL(5, 0)])
print(getDEHL(1.5, 15.0), [hex(x) for x in getDEHL(1.5, 15.0)])
print(getDEHL(1.5, 17.0), [hex(x) for x in getDEHL(1.5, 17.0)])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/beep.py
|
beep.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
from api.constants import TYPE
from api.constants import SCOPE
from api.constants import CLASS
from api.constants import KIND
from api.constants import CONVENTION
import api.errmsg
import api.global_ as gl
import api.check as check
from api.debug import __DEBUG__
from api.errmsg import error
from api.config import OPTIONS
from api.global_ import optemps
from api.errors import InvalidLoopError
from api.errors import InvalidOperatorError
from api.errors import InvalidBuiltinFunctionError
from api.errors import InternalError
from libzxbpp import zxbpp
from . import backend
from .backend.__float import _float
import symbols
from symbols.type_ import Type
from .translatorvisitor import TranslatorVisitor
import arch.zx48k # TODO: put this in global
__all__ = ['Translator',
'VarTranslator',
'FunctionTranslator']
JumpTable = namedtuple('JumpTable', ('label', 'addresses'))
LabelledData = namedtuple('LabelledData', ('label', 'data'))
class Translator(TranslatorVisitor):
""" ZX Spectrum translator
"""
def visit_NOP(self, node):
pass # nothing to do
def visit_CLS(self, node):
self.ic_call('CLS', 0)
backend.REQUIRES.add('cls.asm')
def visit_NUMBER(self, node):
__DEBUG__('NUMBER ' + str(node))
yield node.value
def visit_STRING(self, node):
__DEBUG__('STRING ' + str(node))
node.t = '#' + self.add_string_label(node.value)
yield node.t
def visit_END(self, node):
yield node.children[0]
__DEBUG__('END')
self.ic_end(node.children[0].t)
def visit_ERROR(self, node):
# Raises an error
yield node.children[0]
self.ic_fparam(TYPE.ubyte, node.children[0].t)
self.ic_call('__ERROR', 0)
backend.REQUIRES.add('error.asm')
def visit_STOP(self, node):
""" Returns to BASIC with an error code
"""
yield node.children[0]
self.ic_fparam(TYPE.ubyte, node.children[0].t)
self.ic_call('__STOP', 0)
self.ic_end(0)
backend.REQUIRES.add('error.asm')
def visit_LET(self, node):
assert isinstance(node.children[0], symbols.VAR)
if self.O_LEVEL < 2 or node.children[0].accessed or node.children[1].token == 'CONST':
yield node.children[1]
__DEBUG__('LET')
self.emit_let_left_part(node)
def visit_POKE(self, node):
ch0 = node.children[0]
ch1 = node.children[1]
yield ch0
yield ch1
if ch0.token == 'VAR' and ch0.class_ != CLASS.const and ch0.scope == SCOPE.global_:
self.ic_store(ch1.type_, '*' + str(ch0.t), ch1.t)
else:
self.ic_store(ch1.type_, str(ch0.t), ch1.t)
def visit_RANDOMIZE(self, node):
yield node.children[0]
self.ic_fparam(node.children[0].type_, node.children[0].t)
self.ic_call('RANDOMIZE', 0)
backend.REQUIRES.add('random.asm')
def visit_LABEL(self, node):
self.ic_label(node.mangled)
for tmp in node.aliased_by:
self.ic_label(tmp.mangled)
def visit_VAR(self, node):
__DEBUG__('{}: VAR {}:{} Scope: {} Class: {}'.format(node.lineno, node.name, node.type_,
SCOPE.to_string(node.scope), CLASS.to_string(node.class_)))
scope = node.scope
if node.t == node.mangled and scope == SCOPE.global_:
return
if node.class_ in (CLASS.label, CLASS.const):
return
p = '*' if node.byref else '' # Indirection prefix
if scope == SCOPE.parameter:
self.ic_pload(node.type_, node.t, p + str(node.offset))
elif scope == SCOPE.local:
offset = node.offset
if node.alias is not None and node.alias.class_ == CLASS.array:
offset -= 1 + 2 * node.alias.count # TODO this is actually NOT implemented
self.ic_pload(node.type_, node.t, p + str(-offset))
def visit_CONST(self, node):
node.t = '#' + (self.traverse_const(node) or '')
yield node.t
def visit_VARARRAY(self, node):
pass
def visit_PARAMDECL(self, node):
assert node.scope == SCOPE.parameter
self.visit_VAR(node)
def visit_UNARY(self, node):
uvisitor = UnaryOpTranslator()
att = 'visit_{}'.format(node.operator)
if hasattr(uvisitor, att):
yield getattr(uvisitor, att)(node)
return
raise InvalidOperatorError(node.operator)
def visit_BUILTIN(self, node):
yield node.operand
bvisitor = BuiltinTranslator()
att = 'visit_{}'.format(node.fname)
if hasattr(bvisitor, att):
yield getattr(bvisitor, att)(node)
return
raise InvalidBuiltinFunctionError(node.fname)
def visit_BINARY(self, node):
yield node.left
yield node.right
ins = {'PLUS': 'add', 'MINUS': 'sub'}.get(node.operator, node.operator.lower())
s = self.TSUFFIX(node.left.type_) # Operands type
self.emit(ins + s, node.t, str(node.left.t), str(node.right.t))
def visit_TYPECAST(self, node):
yield node.operand
assert node.operand.type_.is_basic
assert node.type_.is_basic
self.ic_cast(node.t, node.operand.type_, node.type_, node.operand.t)
def visit_FUNCDECL(self, node):
# Delay emission of functions until the end of the main code
gl.FUNCTIONS.append(node.entry)
def visit_CALL(self, node):
yield node.args # arglist
if node.entry.convention == CONVENTION.fastcall:
if len(node.args) > 0: # At least 1 parameter
self.ic_fparam(node.args[0].type_, optemps.new_t())
self.ic_call(node.entry.mangled, 0) # Procedure call. 0 = discard return
if node.entry.kind == KIND.function and node.entry.type_ == self.TYPE(TYPE.string):
self.ic_call('__MEM_FREE', 0) # Discard string return value if the called function has any
backend.REQUIRES.add('free.asm')
def visit_ARGLIST(self, node):
for i in range(len(node) - 1, -1, -1): # visit in reverse order
yield node[i]
if isinstance(node.parent, symbols.ARRAYACCESS) and OPTIONS.arrayCheck.value:
upper = node.parent.entry.bounds[i].upper
lower = node.parent.entry.bounds[i].lower
self.ic_param(gl.PTR_TYPE, upper - lower)
def visit_ARGUMENT(self, node):
if not node.byref:
if node.value.token in ('VAR', 'PARAMDECL') and \
node.type_.is_dynamic and node.value.t[0] == '$':
# Duplicate it in the heap
assert (node.value.scope in (SCOPE.local, SCOPE.parameter))
if node.value.scope == SCOPE.local:
self.ic_pload(node.type_, node.t, str(-node.value.offset))
else: # PARAMETER
self.ic_pload(node.type_, node.t, str(node.value.offset))
else:
yield node.value
self.ic_param(node.type_, node.t)
else:
scope = node.value.scope
if node.t[0] == '_':
t = optemps.new_t()
else:
t = node.t
if scope == SCOPE.global_:
self.ic_load(TYPE.uinteger, t, '#' + node.mangled)
elif scope == SCOPE.parameter: # A function has used a parameter as an argument to another function call
if not node.value.byref: # It's like a local variable
self.ic_paddr(node.value.offset, t)
else:
self.ic_pload(TYPE.uinteger, t, str(node.value.offset))
elif scope == SCOPE.local:
self.ic_paddr(-node.value.offset, t)
self.ic_param(TYPE.uinteger, t)
def visit_ARRAYLOAD(self, node):
scope = node.entry.scope
if node.offset is None:
yield node.args
if scope == SCOPE.global_:
self.ic_aload(node.type_, node.entry.t, node.entry.mangled)
elif scope == SCOPE.parameter:
self.ic_paload(node.type_, node.t, '*{}'.format(node.entry.offset))
elif scope == SCOPE.local:
self.ic_paload(node.type_, node.t, -node.entry.offset)
else:
offset = node.offset
if scope == SCOPE.global_:
self.ic_load(node.type_, node.entry.t, '%s + %i' % (node.entry.t, offset))
elif scope == SCOPE.parameter:
self.ic_pload(node.type_, node.t, node.entry.offset - offset)
elif scope == SCOPE.local:
t1 = optemps.new_t()
t2 = optemps.new_t()
t3 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t1, -(node.entry.offset - self.TYPE(gl.PTR_TYPE).size))
self.ic_add(gl.PTR_TYPE, t2, t1, node.offset)
self.ic_load(node.type_, t3, '*$%s' % t2)
def visit_ARRAYCOPY(self, node):
tr = node.children[0]
scope = tr.scope
if scope == SCOPE.global_:
t1 = "#%s" % tr.data_label
elif scope == SCOPE.parameter:
t1 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t1, '%i' % (tr.offset - self.TYPE(gl.PTR_TYPE).size))
elif scope == SCOPE.local:
t1 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t1, '%i' % -(tr.offset - self.TYPE(gl.PTR_TYPE).size))
tr = node.children[1]
scope = tr.scope
if scope == SCOPE.global_:
t2 = "#%s" % tr.data_label
elif scope == SCOPE.parameter:
t2 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t2, '%i' % (tr.offset - self.TYPE(gl.PTR_TYPE).size))
elif scope == SCOPE.local:
t2 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t2, '%i' % -(tr.offset - self.TYPE(gl.PTR_TYPE).size))
t = optemps.new_t()
if tr.type_ != Type.string:
self.ic_load(gl.PTR_TYPE, t, '%i' % tr.size)
self.ic_memcopy(t1, t2, t)
else:
self.ic_load(gl.PTR_TYPE, '%i' % tr.count)
self.ic_call('STR_ARRAYCOPY', 0)
backend.REQUIRES.add('strarraycpy.asm')
def visit_LETARRAY(self, node):
if self.O_LEVEL > 1 and not node.children[0].entry.accessed:
return
yield node.children[1] # Right expression
arr = node.children[0] # Array access
scope = arr.scope
if arr.offset is None:
yield arr
if scope == SCOPE.global_:
self.ic_astore(arr.type_, arr.entry.mangled, node.children[1].t)
elif scope == SCOPE.parameter:
# HINT: Arrays are always passed ByREF
self.ic_pastore(arr.type_, '*{}'.format(arr.entry.offset), node.children[1].t)
elif scope == SCOPE.local:
self.ic_pastore(arr.type_, -arr.entry.offset, node.children[1].t)
else:
name = arr.entry.data_label
if scope == SCOPE.global_:
self.ic_store(arr.type_, '%s + %i' % (name, arr.offset), node.children[1].t)
elif scope == SCOPE.local:
t1 = optemps.new_t()
t2 = optemps.new_t()
self.ic_pload(gl.PTR_TYPE, t1, -(arr.entry.offset - self.TYPE(gl.PTR_TYPE).size))
self.ic_add(gl.PTR_TYPE, t2, t1, arr.offset)
if arr.type_ == Type.string:
self.ic_store(arr.type_, '*{}'.format(t2), node.children[1].t)
else:
self.ic_store(arr.type_, t2, node.children[1].t)
else:
raise InternalError("Invalid scope {} for variable '{}'".format(scope, arr.entry.name))
def visit_LETSUBSTR(self, node):
yield node.children[3]
if check.is_temporary_value(node.children[3]):
self.ic_param(TYPE.string, node.children[3].t)
self.ic_param(TYPE.ubyte, 1)
else:
self.ic_param(gl.PTR_TYPE, node.children[3].t)
self.ic_param(TYPE.ubyte, 0)
yield node.children[1]
self.ic_param(gl.PTR_TYPE, node.children[1].t)
yield node.children[2]
self.ic_param(gl.PTR_TYPE, node.children[2].t)
self.ic_fparam(gl.PTR_TYPE, node.children[0].t)
self.ic_call('__LETSUBSTR', 0)
backend.REQUIRES.add('letsubstr.asm')
def visit_LETARRAYSUBSTR(self, node):
if self.O_LEVEL > 1 and not node.children[0].entry.accessed:
return
expr = node.children[3] # right expression
yield expr
if check.is_temporary_value(expr):
self.ic_param(TYPE.string, expr.t)
self.ic_param(TYPE.ubyte, 1)
else:
self.ic_param(gl.PTR_TYPE, expr.t)
self.ic_param(TYPE.ubyte, 0)
yield node.children[1]
self.ic_param(gl.PTR_TYPE, node.children[1].t)
yield node.children[2]
self.ic_param(gl.PTR_TYPE, node.children[2].t)
node_ = node.children[0]
scope = node_.scope
entry = node_.entry
# Address of an array element.
if node_.offset is None:
yield node_
if scope == SCOPE.global_:
self.ic_aload(gl.PTR_TYPE, node_.t, entry.mangled)
elif scope == SCOPE.parameter: # TODO: These 2 are never used!??
self.ic_paload(gl.PTR_TYPE, node_.t, entry.offset)
elif scope == SCOPE.local:
self.ic_paload(gl.PTR_TYPE, node_.t, -entry.offset)
else:
offset = node_.offset
if scope == SCOPE.global_:
self.ic_load(gl.PTR_TYPE, entry.t, '%s.__DATA__ + %i' % (entry.mangled, offset))
elif scope == SCOPE.parameter:
self.ic_pload(gl.PTR_TYPE, node_.t, entry.offset - offset)
elif scope == SCOPE.local:
self.ic_pload(gl.PTR_TYPE, node_.t, -(entry.offset - offset))
self.ic_fparam(gl.PTR_TYPE, node.children[0].t)
self.ic_call('__LETSUBSTR', 0)
backend.REQUIRES.add('letsubstr.asm')
def visit_ARRAYACCESS(self, node):
yield node.arglist
def visit_STRSLICE(self, node):
yield node.string
if node.string.token == 'STRING' or \
node.string.token == 'VAR' and node.string.scope == SCOPE.global_:
self.ic_param(gl.PTR_TYPE, node.string.t)
# Now emit the slicing indexes
yield node.lower
self.ic_param(node.lower.type_, node.lower.t)
yield node.upper
self.ic_param(node.upper.type_, node.upper.t)
if (node.string.token in ('VAR', 'PARAMDECL') and
node.string.mangled[0] == '_' or node.string.token == 'STRING'):
self.ic_fparam(TYPE.ubyte, 0)
else:
self.ic_fparam(TYPE.ubyte, 1) # If the argument is not a variable, it must be freed
self.ic_call('__STRSLICE', self.TYPE(gl.PTR_TYPE).size)
backend.REQUIRES.add('strslice.asm')
def visit_FUNCCALL(self, node):
yield node.args
if node.entry.convention == CONVENTION.fastcall:
if len(node.args) > 0: # At least 1
self.ic_fparam(node.args[0].type_, optemps.new_t())
self.ic_call(node.entry.mangled, node.entry.size)
def visit_RESTORE(self, node):
if not gl.DATA_IS_USED:
return # If no READ is used, ignore all DATA related statements
lbl = gl.DATA_LABELS[node.args[0].name]
gl.DATA_LABELS_REQUIRED.add(lbl)
self.ic_fparam(node.args[0].type_, '#' + lbl)
self.ic_call('__RESTORE', 0)
backend.REQUIRES.add('read_restore.asm')
def visit_READ(self, node):
self.ic_fparam(TYPE.ubyte, '#' + str(self.DATA_TYPES[self.TSUFFIX(node.args[0].type_)]))
self.ic_call('__READ', node.args[0].type_.size)
if isinstance(node.args[0], symbols.ARRAYACCESS):
arr = node.args[0]
t = api.global_.optemps.new_t()
scope = arr.scope
if arr.offset is None:
yield arr
if scope == SCOPE.global_:
self.ic_astore(arr.type_, arr.entry.mangled, t)
elif scope == SCOPE.parameter:
self.ic_pastore(arr.type_, arr.entry.offset, t)
elif scope == SCOPE.local:
self.ic_pastore(arr.type_, -arr.entry.offset, t)
else:
name = arr.entry.mangled
if scope == SCOPE.global_:
self.ic_store(arr.type_, '%s + %i' % (name, arr.offset), t)
elif scope == SCOPE.parameter:
self.ic_pstore(arr.type_, arr.entry.offset - arr.offset, t)
elif scope == SCOPE.local:
self.ic_pstore(arr.type_, -(arr.entry.offset - arr.offset), t)
else:
self.emit_var_assign(node.args[0], t=api.global_.optemps.new_t())
backend.REQUIRES.add('read_restore.asm')
# region Control Flow Sentences
# -----------------------------------------------------------------------------------------------------
# Control Flow Compound sentences FOR, IF, WHILE, DO UNTIL...
# -----------------------------------------------------------------------------------------------------
def visit_DO_LOOP(self, node):
loop_label = backend.tmp_label()
end_loop = backend.tmp_label()
self.LOOPS.append(('DO', end_loop, loop_label)) # Saves which labels to jump upon EXIT or CONTINUE
self.ic_label(loop_label)
if node.children:
yield node.children[0]
self.ic_jump(loop_label)
self.ic_label(end_loop)
self.LOOPS.pop()
# del loop_label, end_loop
def visit_DO_UNTIL(self, node):
return self.visit_UNTIL_DO(node)
def visit_DO_WHILE(self, node):
loop_label = backend.tmp_label()
end_loop = backend.tmp_label()
continue_loop = backend.tmp_label()
if node.token == 'WHILE_DO':
self.ic_jump(continue_loop)
self.ic_label(loop_label)
self.LOOPS.append(('DO', end_loop, continue_loop)) # Saves which labels to jump upon EXIT or CONTINUE
if len(node.children) > 1:
yield node.children[1]
self.ic_label(continue_loop)
yield node.children[0]
self.ic_jnzero(node.children[0].type_, node.children[0].t, loop_label)
self.ic_label(end_loop)
self.LOOPS.pop()
# del loop_label, end_loop, continue_loop
def visit_EXIT_DO(self, node):
self.ic_jump(self.loop_exit_label('DO'))
def visit_EXIT_WHILE(self, node):
self.ic_jump(self.loop_exit_label('WHILE'))
def visit_EXIT_FOR(self, node):
self.ic_jump(self.loop_exit_label('FOR'))
def visit_CONTINUE_DO(self, node):
self.ic_jump(self.loop_cont_label('DO'))
def visit_CONTINUE_WHILE(self, node):
self.ic_jump(self.loop_cont_label('WHILE'))
def visit_CONTINUE_FOR(self, node):
self.ic_jump(self.loop_cont_label('FOR'))
def visit_FOR(self, node):
loop_label_start = backend.tmp_label()
loop_label_gt = backend.tmp_label()
end_loop = backend.tmp_label()
loop_body = backend.tmp_label()
loop_continue = backend.tmp_label()
type_ = node.children[0].type_
self.LOOPS.append(('FOR', end_loop, loop_continue)) # Saves which label to jump upon EXIT FOR and CONTINUE FOR
yield node.children[1] # Gets starting value (lower limit)
self.emit_let_left_part(node) # Stores it in the iterator variable
self.ic_jump(loop_label_start)
# FOR body statements
self.ic_label(loop_body)
yield node.children[4]
# Jump here to continue next iteration
self.ic_label(loop_continue)
# VAR = VAR + STEP
yield node.children[0] # Iterator Var
yield node.children[3] # Step
t = optemps.new_t()
self.ic_add(type_, t, node.children[0].t, node.children[3].t)
self.emit_let_left_part(node, t)
# Loop starts here
self.ic_label(loop_label_start)
# Emmit condition
if check.is_number(node.children[3]) or check.is_unsigned(node.children[3].type_):
direct = True
else:
direct = False
yield node.children[3] # Step
self.ic_jgezero(type_, node.children[3].t, loop_label_gt)
if not direct or node.children[3].value < 0: # Here for negative steps
# Compares if var < limit2
yield node.children[0] # Value of var
yield node.children[2] # Value of limit2
self.ic_lt(type_, node.t, node.children[0].t, node.children[2].t)
self.ic_jzero(TYPE.ubyte, node.t, loop_body)
if not direct:
self.ic_jump(end_loop)
self.ic_label(loop_label_gt)
if not direct or node.children[3].value >= 0: # Here for positive steps
# Compares if var > limit2
yield node.children[0] # Value of var
yield node.children[2] # Value of limit2
self.ic_gt(type_, node.t, node.children[0].t, node.children[2].t)
self.ic_jzero(TYPE.ubyte, node.t, loop_body)
self.ic_label(end_loop)
self.LOOPS.pop()
def visit_GOTO(self, node):
self.ic_jump(node.children[0].mangled)
def visit_GOSUB(self, node):
self.ic_call(node.children[0].mangled, 0)
def visit_ON_GOTO(self, node):
table_label = backend.tmp_label()
self.ic_param(gl.PTR_TYPE, '#' + table_label)
yield node.children[0]
self.ic_fparam(node.children[0].type_, node.children[0].t)
self.ic_call('__ON_GOTO', 0)
self.JUMP_TABLES.append(JumpTable(table_label, node.children[1:]))
backend.REQUIRES.add('ongoto.asm')
def visit_ON_GOSUB(self, node):
table_label = backend.tmp_label()
self.ic_param(gl.PTR_TYPE, '#' + table_label)
yield node.children[0]
self.ic_fparam(node.children[0].type_, node.children[0].t)
self.ic_call('__ON_GOSUB', 0)
self.JUMP_TABLES.append(JumpTable(table_label, node.children[1:]))
backend.REQUIRES.add('ongoto.asm')
def visit_CHKBREAK(self, node):
if self.PREV_TOKEN != node.token:
self.ic_inline('push hl', node.children[0].t)
self.ic_fparam(gl.PTR_TYPE, node.children[0].t)
self.ic_call('CHECK_BREAK', 0)
backend.REQUIRES.add('break.asm')
def visit_IF(self, node):
assert 1 < len(node.children) < 4, 'IF nodes: %i' % len(node.children)
yield node.children[0]
if_label_else = backend.tmp_label()
if_label_endif = backend.tmp_label()
if len(node.children) == 3: # Has else?
self.ic_jzero(node.children[0].type_, node.children[0].t, if_label_else)
else:
self.ic_jzero(node.children[0].type_, node.children[0].t, if_label_endif)
yield node.children[1] # THEN...
if len(node.children) == 3: # Has else?
self.ic_jump(if_label_endif)
self.ic_label(if_label_else)
yield node.children[2]
self.ic_label(if_label_endif)
def visit_RETURN(self, node):
if len(node.children) == 2: # Something to return?
yield node.children[1]
self.ic_ret(node.children[1].type_, node.children[1].t, '%s__leave' % node.children[0].mangled)
elif len(node.children) == 1:
self.ic_return('%s__leave' % node.children[0].mangled)
else:
self.ic_leave('__fastcall__')
def visit_UNTIL_DO(self, node):
loop_label = backend.tmp_label()
end_loop = backend.tmp_label()
continue_loop = backend.tmp_label()
if node.token == 'UNTIL_DO':
self.ic_jump(continue_loop)
self.ic_label(loop_label)
self.LOOPS.append(('DO', end_loop, continue_loop)) # Saves which labels to jump upon EXIT or CONTINUE
if len(node.children) > 1:
yield node.children[1]
self.ic_label(continue_loop)
yield node.children[0] # Condition
self.ic_jzero(node.children[0].type_, node.children[0].t, loop_label)
self.ic_label(end_loop)
self.LOOPS.pop()
# del loop_label, end_loop, continue_loop
def visit_WHILE(self, node):
loop_label = backend.tmp_label()
end_loop = backend.tmp_label()
self.LOOPS.append(('WHILE', end_loop, loop_label)) # Saves which labels to jump upon EXIT or CONTINUE
self.ic_label(loop_label)
yield node.children[0]
self.ic_jzero(node.children[0].type_, node.children[0].t, end_loop)
if len(node.children) > 1:
yield node.children[1]
self.ic_jump(loop_label)
self.ic_label(end_loop)
self.LOOPS.pop()
def visit_WHILE_DO(self, node):
return self.visit_DO_WHILE(node)
# endregion
# region [Drawing Primitives]
# -----------------------------------------------------------------------------------------------------
# Drawing Primitives PLOT, DRAW, DRAW3, CIRCLE
# -----------------------------------------------------------------------------------------------------
def visit_PLOT(self, node):
TMP_HAS_ATTR = self.check_attr(node, 2)
yield TMP_HAS_ATTR
yield node.children[0]
self.ic_param(node.children[0].type_, node.children[0].t)
yield node.children[1]
self.ic_fparam(node.children[1].type_, node.children[1].t)
self.ic_call('PLOT', 0)
backend.REQUIRES.add('plot.asm')
self.HAS_ATTR = (TMP_HAS_ATTR is not None)
def visit_DRAW(self, node):
TMP_HAS_ATTR = self.check_attr(node, 2)
yield TMP_HAS_ATTR
yield node.children[0]
self.ic_param(node.children[0].type_, node.children[0].t)
yield node.children[1]
self.ic_fparam(node.children[1].type_, node.children[1].t)
self.ic_call('DRAW', 0)
backend.REQUIRES.add('draw.asm')
self.HAS_ATTR = (TMP_HAS_ATTR is not None)
def visit_DRAW3(self, node):
TMP_HAS_ATTR = self.check_attr(node, 3)
yield TMP_HAS_ATTR
yield node.children[0]
self.ic_param(node.children[0].type_, node.children[0].t)
yield node.children[1]
self.ic_param(node.children[1].type_, node.children[1].t)
yield node.children[2]
self.ic_fparam(node.children[2].type_, node.children[2].t)
self.ic_call('DRAW3', 0)
backend.REQUIRES.add('draw3.asm')
self.HAS_ATTR = (TMP_HAS_ATTR is not None)
def visit_CIRCLE(self, node):
TMP_HAS_ATTR = self.check_attr(node, 3)
yield TMP_HAS_ATTR
yield node.children[0]
self.ic_param(node.children[0].type_, node.children[0].t)
yield node.children[1]
self.ic_param(node.children[1].type_, node.children[1].t)
yield node.children[2]
self.ic_fparam(node.children[2].type_, node.children[2].t)
self.ic_call('CIRCLE', 0)
backend.REQUIRES.add('circle.asm')
self.HAS_ATTR = (TMP_HAS_ATTR is not None)
# endregion
# region [I/O Statements]
# -----------------------------------------------------------------------------------------------------
# PRINT, LOAD, SAVE and I/O statements
# -----------------------------------------------------------------------------------------------------
def visit_OUT(self, node):
yield node.children[0]
yield node.children[1]
self.ic_out(node.children[0].t, node.children[1].t)
def visit_PRINT(self, node):
for i in node.children:
yield i
# Print subcommands (AT, OVER, INK, etc... must be skipped here)
if i.token in ('PRINT_TAB', 'PRINT_AT', 'PRINT_COMMA',) + self.ATTR_TMP:
continue
self.ic_fparam(i.type_, i.t)
self.ic_call('__PRINT' + self.TSUFFIX(i.type_).upper(), 0)
backend.REQUIRES.add('print' + self.TSUFFIX(i.type_).lower() + '.asm')
for i in node.children:
if i.token in self.ATTR_TMP or self.has_control_chars(i):
self.HAS_ATTR = True
break
if node.eol:
if self.HAS_ATTR:
self.ic_call('PRINT_EOL_ATTR', 0)
backend.REQUIRES.add('print_eol_attr.asm')
self.HAS_ATTR = False
else:
self.ic_call('PRINT_EOL', 0)
backend.REQUIRES.add('print.asm')
else:
self.norm_attr()
def visit_PRINT_AT(self, node):
yield node.children[0]
self.ic_param(TYPE.ubyte, node.children[0].t)
yield node.children[1]
self.ic_fparam(TYPE.ubyte, node.children[1].t)
self.ic_call('PRINT_AT', 0) # Procedure call. Discard return
backend.REQUIRES.add('print.asm')
def visit_PRINT_TAB(self, node):
yield node.children[0]
self.ic_fparam(TYPE.ubyte, node.children[0].t)
self.ic_call('PRINT_TAB', 0)
backend.REQUIRES.add('print.asm')
def visit_PRINT_COMMA(self, node):
self.ic_call('PRINT_COMMA', 0)
backend.REQUIRES.add('print.asm')
def visit_LOAD(self, node):
yield node.children[0]
self.ic_param(TYPE.string, node.children[0].t)
yield node.children[1]
self.ic_param(gl.PTR_TYPE, node.children[1].t)
yield node.children[2]
self.ic_param(gl.PTR_TYPE, node.children[2].t)
self.ic_param(TYPE.ubyte, int(node.token == 'LOAD'))
self.ic_call('LOAD_CODE', 0)
backend.REQUIRES.add('load.asm')
def visit_SAVE(self, node):
yield (node.children[0])
self.ic_param(TYPE.string, node.children[0].t)
yield (node.children[1])
self.ic_param(gl.PTR_TYPE, node.children[1].t)
yield node.children[2]
self.ic_param(gl.PTR_TYPE, node.children[2].t)
self.ic_call('SAVE_CODE', 0)
backend.REQUIRES.add('save.asm')
def visit_VERIFY(self, node):
return self.visit_LOAD(node)
def visit_BORDER(self, node):
yield node.children[0]
self.ic_fparam(TYPE.ubyte, node.children[0].t)
self.ic_call('BORDER', 0)
backend.REQUIRES.add('border.asm')
def visit_BEEP(self, node):
if node.children[0].token == node.children[1].token == 'NUMBER': # BEEP <const>, <const>
DE, HL = arch.zx48k.beep.getDEHL(float(node.children[0].t), float(node.children[1].t))
self.ic_param(TYPE.uinteger, HL)
self.ic_fparam(TYPE.uinteger, DE)
self.ic_call('__BEEPER', 0) # Procedure call. Discard return
backend.REQUIRES.add('beeper.asm')
else:
yield node.children[1]
self.ic_param(TYPE.float_, node.children[1].t)
yield node.children[0]
self.ic_fparam(TYPE.float_, node.children[0].t)
self.ic_call('BEEP', 0)
backend.REQUIRES.add('beep.asm')
def visit_PAUSE(self, node):
yield node.children[0]
self.ic_fparam(node.children[0].type_, node.children[0].t)
self.ic_call('__PAUSE', 0)
backend.REQUIRES.add('pause.asm')
# endregion
# region [ATTR Sentences]
# -----------------------------------------------------------------------
# ATTR sentences: INK, PAPER, BRIGHT, FLASH, INVERSE, OVER, ITALIC, BOLD
# -----------------------------------------------------------------------
def visit_ATTR_sentence(self, node):
yield node.children[0]
self.ic_fparam(TYPE.ubyte, node.children[0].t)
self.ic_call(node.token, 0)
backend.REQUIRES.add('%s.asm' % node.token.lower())
self.HAS_ATTR = True
def visit_INK(self, node):
return self.visit_ATTR_sentence(node)
def visit_PAPER(self, node):
return self.visit_ATTR_sentence(node)
def visit_BRIGHT(self, node):
return self.visit_ATTR_sentence(node)
def visit_FLASH(self, node):
return self.visit_ATTR_sentence(node)
def visit_INVERSE(self, node):
return self.visit_ATTR_sentence(node)
def visit_OVER(self, node):
return self.visit_ATTR_sentence(node)
def visit_BOLD(self, node):
return self.visit_ATTR_sentence(node)
def visit_ITALIC(self, node):
return self.visit_ATTR_sentence(node)
# endregion
# region [Other Sentences]
# -----------------------------------------------------------------------------------------------------
# Other Sentences, like ASM, etc..
# -----------------------------------------------------------------------------------------------------
def visit_ASM(self, node):
self.ic_inline(node.asm, node.lineno)
# endregion
# region [Helpers]
# --------------------------------------
# Helpers
# --------------------------------------
def emit_var_assign(self, var, t):
""" Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...)
"""
p = '*' if var.byref else '' # Indirection prefix
if self.O_LEVEL > 1 and not var.accessed:
return
if not var.type_.is_basic:
raise NotImplementedError()
if var.scope == SCOPE.global_:
self.ic_store(var.type_, var.mangled, t)
elif var.scope == SCOPE.parameter:
self.ic_pstore(var.type_, p + str(var.offset), t)
elif var.scope == SCOPE.local:
if var.alias is not None and var.alias.class_ == CLASS.array:
var.offset -= 1 + 2 * var.alias.count
self.ic_pstore(var.type_, p + str(-var.offset), t)
def emit_let_left_part(self, node, t=None):
var = node.children[0]
expr = node.children[1]
if t is None:
t = expr.t # TODO: Check
return self.emit_var_assign(var, t)
# endregion
# region [Static Methods]
# --------------------------------------
# Static Methods
# --------------------------------------
def loop_exit_label(self, loop_type):
""" Returns the label for the given loop type which
exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
"""
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][1]
raise InvalidLoopError(loop_type)
def loop_cont_label(self, loop_type):
""" Returns the label for the given loop type which
continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
"""
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][2]
raise InvalidLoopError(loop_type)
@classmethod
def default_value(cls, type_, expr): # TODO: This function must be moved to api.xx
""" Returns a list of bytes (as hexadecimal 2 char string)
"""
assert isinstance(type_, symbols.TYPE)
assert type_.is_basic
assert check.is_static(expr)
if isinstance(expr, (symbols.CONST, symbols.VAR)): # a constant expression like @label + 1
if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string)):
error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name))
return ['<ERROR>']
val = Translator.traverse_const(expr)
if type_.size == 1: # U/byte
if expr.type_.size != 1:
return ['#({0}) & 0xFF'.format(val)]
else:
return ['#{0}'.format(val)]
if type_.size == 2: # U/integer
if expr.type_.size != 2:
return ['##({0}) & 0xFFFF'.format(val)]
else:
return ['##{0}'.format(val)]
if type_ == cls.TYPE(TYPE.fixed):
return ['0000', '##({0}) & 0xFFFF'.format(val)]
# U/Long
return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)]
if type_ == cls.TYPE(TYPE.float_):
C, DE, HL = _float(expr.value)
C = C[:-1] # Remove 'h' suffix
if len(C) > 2:
C = C[-2:]
DE = DE[:-1] # Remove 'h' suffix
if len(DE) > 4:
DE = DE[-4:]
elif len(DE) < 3:
DE = '00' + DE
HL = HL[:-1] # Remove 'h' suffix
if len(HL) > 4:
HL = HL[-4:]
elif len(HL) < 3:
HL = '00' + HL
return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]]
if type_ == cls.TYPE(TYPE.fixed):
value = 0xFFFFFFFF & int(expr.value * 2 ** 16)
else:
value = int(expr.value)
result = [value, value >> 8, value >> 16, value >> 24]
result = ['%02X' % (v & 0xFF) for v in result]
return result[:type_.size]
@staticmethod
def array_default_value(type_, values):
""" Returns a list of bytes (as hexadecimal 2 char string)
which represents the array initial value.
"""
if not isinstance(values, list):
return Translator.default_value(type_, values)
l = []
for row in values:
l.extend(Translator.array_default_value(type_, row))
return l
@staticmethod
def has_control_chars(i):
""" Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc
"""
if not hasattr(i, 'type_'):
return False
if i.type_ != Type.string:
return False
if i.token in ('VAR', 'PARAMDECL'):
return True # We don't know what an alphanumeric variable will hold
if i.token == 'STRING':
for c in i.value:
if 15 < ord(c) < 22: # is it an attr char?
return True
return False
for j in i.children:
if Translator.has_control_chars(j):
return True
return False
# endregion
""" END """
class VarTranslator(TranslatorVisitor):
""" Var Translator
This translator emits memory var space
"""
def visit_LABEL(self, node):
self.ic_label(node.mangled)
for tmp in node.aliased_by:
self.ic_label(tmp.mangled)
def visit_VARDECL(self, node):
entry = node.entry
if not entry.accessed:
api.errmsg.warning_not_used(entry.lineno, entry.name)
if self.O_LEVEL > 1: # HINT: Unused vars not compiled
return
if entry.addr is not None:
addr = self.traverse_const(entry.addr) if isinstance(entry.addr, symbols.SYMBOL) else entry.addr
self.ic_deflabel(entry.mangled, addr)
for entry in entry.aliased_by:
self.ic_deflabel(entry.mangled, entry.addr)
elif entry.alias is None:
for alias in entry.aliased_by:
self.ic_label(alias.mangled)
if entry.default_value is None:
self.ic_var(entry.mangled, entry.size)
else:
if isinstance(entry.default_value, symbols.CONST) and entry.default_value.token == 'CONST':
self.ic_varx(node.mangled, node.type_, [self.traverse_const(entry.default_value)])
else:
self.ic_vard(node.mangled, Translator.default_value(node.type_, entry.default_value))
def visit_ARRAYDECL(self, node):
entry = node.entry
assert entry.default_value is None or entry.addr is None, "Cannot use address and default_value at once"
if not entry.accessed:
api.errmsg.warning_not_used(entry.lineno, entry.name)
if self.O_LEVEL > 1:
return
bound_ptrs = [] # Bound tables pointers (empty if not used)
lbound_label = entry.mangled + '.__LBOUND__'
ubound_label = entry.mangled + '.__UBOUND__'
if entry.lbound_used or entry.ubound_used:
bound_ptrs = ['0', '0'] # NULL by default
if entry.lbound_used:
bound_ptrs[0] = lbound_label
if entry.ubound_used:
bound_ptrs[1] = ubound_label
data_label = entry.data_label
idx_table_label = backend.tmp_label()
l = ['%04X' % (len(node.bounds) - 1)] # Number of dimensions - 1
for bound in node.bounds[1:]:
l.append('%04X' % (bound.upper - bound.lower + 1))
l.append('%02X' % node.type_.size)
arr_data = []
if entry.addr:
self.ic_deflabel(data_label, "%s" % entry.addr)
else:
if entry.default_value is not None:
arr_data = Translator.array_default_value(node.type_, entry.default_value)
else:
arr_data = ['00'] * node.size
for alias in entry.aliased_by:
offset = 1 + 2 * TYPE.size(gl.PTR_TYPE) + alias.offset # TODO: Generalize for multi-arch
self.ic_deflabel(alias.mangled, '%s + %i' % (entry.mangled, offset))
self.ic_varx(node.mangled, gl.PTR_TYPE, [idx_table_label])
if entry.addr:
self.ic_varx(entry.data_ptr_label, gl.PTR_TYPE, [self.traverse_const(entry.addr)])
if bound_ptrs:
self.ic_data(gl.PTR_TYPE, bound_ptrs)
else:
self.ic_varx(entry.data_ptr_label, gl.PTR_TYPE, [data_label])
if bound_ptrs:
self.ic_data(gl.PTR_TYPE, bound_ptrs)
self.ic_vard(data_label, arr_data)
self.ic_vard(idx_table_label, l)
if entry.lbound_used:
l = ['%04X' % bound.lower for bound in node.bounds]
self.ic_vard(lbound_label, l)
if entry.ubound_used:
l = ['%04X' % bound.upper for bound in node.bounds]
self.ic_vard(ubound_label, l)
class UnaryOpTranslator(TranslatorVisitor):
""" UNARY sub-visitor. E.g. -a or bNot pi
"""
def visit_MINUS(self, node):
yield node.operand
self.ic_neg(node.type_, node.t, node.operand.t)
def visit_NOT(self, node):
yield node.operand
self.ic_not(node.operand.type_, node.t, node.operand.t)
def visit_BNOT(self, node):
yield node.operand
self.ic_bnot(node.operand.type_, node.t, node.operand.t)
def visit_ADDRESS(self, node):
scope = node.operand.scope
if node.operand.token == 'ARRAYACCESS':
yield node.operand
# Address of an array element.
if scope == SCOPE.global_:
self.ic_aaddr(node.t, node.operand.entry.mangled)
elif scope == SCOPE.parameter:
self.ic_paaddr(node.t, '*{}'.format(node.operand.entry.offset))
elif scope == SCOPE.local:
self.ic_paaddr(node.t, -node.operand.entry.offset)
else: # It's a scalar variable
if scope == SCOPE.global_:
self.ic_load(node.type_, node.t, '#' + node.operand.t)
elif scope == SCOPE.parameter:
self.ic_paddr(node.operand.offset + node.operand.type_.size % 2, node.t)
elif scope == SCOPE.local:
self.ic_paddr(-node.operand.offset, node.t)
class BuiltinTranslator(TranslatorVisitor):
""" BUILTIN functions visitor. Eg. LEN(a$) or SIN(x)
"""
REQUIRES = backend.REQUIRES
# region STRING Functions
def visit_INKEY(self, node):
self.ic_call('INKEY', Type.string.size)
backend.REQUIRES.add('inkey.asm')
def visit_IN(self, node):
self.ic_in(node.children[0].t)
def visit_CODE(self, node):
self.ic_fparam(gl.PTR_TYPE, node.operand.t)
if node.operand.token not in ('STRING', 'VAR', 'PARAMDECL') and node.operand.t != '_':
self.ic_fparam(TYPE.ubyte, 1) # If the argument is not a variable, it must be freed
else:
self.ic_fparam(TYPE.ubyte, 0)
self.ic_call('__ASC', Type.ubyte.size) # Expect a char code
backend.REQUIRES.add('asc.asm')
def visit_CHR(self, node):
self.ic_fparam(gl.STR_INDEX_TYPE, len(node.operand)) # Number of args
self.ic_call('CHR', node.size)
backend.REQUIRES.add('chr.asm')
def visit_STR(self, node):
self.ic_fparam(TYPE.float_, node.children[0].t)
self.ic_call('__STR_FAST', node.type_.size)
backend.REQUIRES.add('str.asm')
def visit_LEN(self, node):
self.ic_lenstr(node.t, node.operand.t)
def visit_VAL(self, node):
self.ic_fparam(gl.PTR_TYPE, node.operand.t)
if node.operand.token not in ('STRING', 'VAR', 'PARAMDECL') and node.operand.t != '_':
self.ic_fparam(TYPE.ubyte, 1) # If the argument is not a variable, it must be freed
else:
self.ic_fparam(TYPE.ubyte, 0)
self.ic_call('VAL', node.type_.size)
backend.REQUIRES.add('val.asm')
# endregion
def visit_ABS(self, node):
self.ic_abs(node.children[0].type_, node.t, node.children[0].t)
def visit_RND(self, node): # A special "ZEROARY" function with no parameters
self.ic_call('RND', Type.float_.size)
backend.REQUIRES.add('random.asm')
def visit_PEEK(self, node):
self.ic_load(node.type_, node.t, '*' + str(node.children[0].t))
# region MATH Functions
def visit_SIN(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('SIN', node.size)
self.REQUIRES.add('sin.asm')
def visit_COS(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('COS', node.size)
self.REQUIRES.add('cos.asm')
def visit_TAN(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('TAN', node.size)
self.REQUIRES.add('tan.asm')
def visit_ASN(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('ASIN', node.size)
self.REQUIRES.add('asin.asm')
def visit_ACS(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('ACOS', node.size)
self.REQUIRES.add('acos.asm')
def visit_ATN(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('ATAN', node.size)
self.REQUIRES.add('atan.asm')
def visit_EXP(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('EXP', node.size)
self.REQUIRES.add('exp.asm')
def visit_LN(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('LN', node.size)
self.REQUIRES.add('logn.asm')
def visit_SGN(self, node):
s = self.TSUFFIX(node.operand.type_)
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('__SGN%s' % s.upper(), node.size)
self.REQUIRES.add('sgn%s.asm' % s)
def visit_SQR(self, node):
self.ic_fparam(node.operand.type_, node.operand.t)
self.ic_call('SQRT', node.size)
self.REQUIRES.add('sqrt.asm')
# endregion
def visit_LBOUND(self, node):
yield node.operands[1]
self.ic_param(gl.BOUND_TYPE, node.operands[1].t)
entry = node.operands[0]
if entry.scope == SCOPE.global_:
self.ic_fparam(gl.PTR_TYPE, '#{}'.format(entry.mangled))
elif entry.scope == SCOPE.parameter:
self.ic_pload(gl.PTR_TYPE, entry.t, entry.offset)
t1 = optemps.new_t()
self.ic_fparam(gl.PTR_TYPE, t1)
elif entry.scope == SCOPE.local:
self.ic_paddr(-entry.offset, entry.t)
t1 = optemps.new_t()
self.ic_fparam(gl.PTR_TYPE, t1)
self.ic_call('__LBOUND', self.TYPE(gl.BOUND_TYPE).size)
backend.REQUIRES.add('bound.asm')
def visit_UBOUND(self, node):
yield node.operands[1]
self.ic_param(gl.BOUND_TYPE, node.operands[1].t)
entry = node.operands[0]
if entry.scope == SCOPE.global_:
self.ic_fparam(gl.PTR_TYPE, '#{}'.format(entry.mangled))
elif entry.scope == SCOPE.parameter:
self.ic_pload(gl.PTR_TYPE, entry.t, entry.offset)
t1 = optemps.new_t()
self.ic_fparam(gl.PTR_TYPE, t1)
elif entry.scope == SCOPE.local:
self.ic_paddr(-entry.offset, entry.t)
t1 = optemps.new_t()
self.ic_fparam(gl.PTR_TYPE, t1)
self.ic_call('__UBOUND', self.TYPE(gl.BOUND_TYPE).size)
backend.REQUIRES.add('bound.asm')
def visit_USR_STR(self, node):
# USR ADDR
self.ic_fparam(TYPE.string, node.children[0].t)
self.ic_call('USR_STR', node.type_.size)
backend.REQUIRES.add('usr_str.asm')
def visit_USR(self, node):
""" Machine code call from basic
"""
self.ic_fparam(gl.PTR_TYPE, node.children[0].t)
self.ic_call('USR', node.type_.size)
backend.REQUIRES.add('usr.asm')
class FunctionTranslator(Translator):
REQUIRES = backend.REQUIRES
def __init__(self, function_list):
if function_list is None:
function_list = []
super(FunctionTranslator, self).__init__()
assert isinstance(function_list, list)
for x in function_list:
assert isinstance(x, symbols.FUNCTION)
self.functions = function_list
def _local_array_load(self, scope, local_var):
t2 = optemps.new_t()
if scope == SCOPE.parameter:
self.ic_pload(gl.PTR_TYPE, t2, '%i' % (local_var.offset - self.TYPE(gl.PTR_TYPE).size))
elif scope == SCOPE.local:
self.ic_pload(gl.PTR_TYPE, t2, '%i' % -(local_var.offset - self.TYPE(gl.PTR_TYPE).size))
self.ic_fparam(gl.PTR_TYPE, t2)
def start(self):
while self.functions:
f = self.functions.pop(0)
__DEBUG__('Translating function ' + f.__repr__())
self.visit(f)
def visit_FUNCTION(self, node):
bound_tables = []
self.ic_label(node.mangled)
if node.convention == CONVENTION.fastcall:
self.ic_enter('__fastcall__')
else:
self.ic_enter(node.locals_size)
for local_var in node.local_symbol_table.values():
if not local_var.accessed: # HINT: This should never happens as values() is already filtered
api.errmsg.warning_not_used(local_var.lineno, local_var.name)
# HINT: Cannot optimize local variables now, since the offsets are already calculated
# if self.O_LEVEL > 1:
# return
if local_var.class_ == CLASS.array and local_var.scope == SCOPE.local:
bound_ptrs = [] # Bound tables pointers (empty if not used)
lbound_label = local_var.mangled + '.__LBOUND__'
ubound_label = local_var.mangled + '.__UBOUND__'
if local_var.lbound_used or local_var.ubound_used:
bound_ptrs = ['0', '0'] # NULL by default
if local_var.lbound_used:
bound_ptrs[0] = lbound_label
if local_var.ubound_used:
bound_ptrs[1] = ubound_label
if bound_ptrs:
zxbpp.ID_TABLE.define('__ZXB_USE_LOCAL_ARRAY_WITH_BOUNDS__', lineno=0)
if local_var.lbound_used:
l = ['%04X' % bound.lower for bound in local_var.bounds]
bound_tables.append(LabelledData(lbound_label, l))
if local_var.ubound_used:
l = ['%04X' % bound.upper for bound in local_var.bounds]
bound_tables.append(LabelledData(ubound_label, l))
l = [len(local_var.bounds) - 1] + [x.count for x in local_var.bounds[1:]] # TODO Check this
q = []
for x in l:
q.append('%02X' % (x & 0xFF))
q.append('%02X' % ((x & 0xFF) >> 8))
q.append('%02X' % local_var.type_.size)
r = []
if local_var.default_value is not None:
r.extend(self.array_default_value(local_var.type_, local_var.default_value))
self.ic_larrd(local_var.offset, q, local_var.size, r, bound_ptrs) # Initializes array bounds
elif local_var.class_ == CLASS.const:
continue
else: # Local vars always defaults to 0, so if 0 we do nothing
if local_var.default_value is not None and local_var.default_value != 0:
if isinstance(local_var.default_value, symbols.CONST) and \
local_var.default_value.token == 'CONST':
self.ic_lvarx(local_var.type_, local_var.offset, [self.traverse_const(local_var.default_value)])
else:
q = self.default_value(local_var.type_, local_var.default_value)
self.ic_lvard(local_var.offset, q)
for i in node.body:
yield i
self.ic_label('%s__leave' % node.mangled)
# Now free any local string from memory.
preserve_hl = False
for local_var in node.local_symbol_table.values():
scope = local_var.scope
if local_var.type_ == self.TYPE(TYPE.string): # Only if it's string we free it
if local_var.class_ != CLASS.array: # Ok just free it
if scope == SCOPE.local or (scope == SCOPE.parameter and not local_var.byref):
if not preserve_hl:
preserve_hl = True
self.ic_exchg()
offset = -local_var.offset if scope == SCOPE.local else local_var.offset
self.ic_fpload(TYPE.string, local_var.t, offset)
self.ic_call('__MEM_FREE', 0)
self.REQUIRES.add('free.asm')
elif local_var.class_ == CLASS.const:
continue
else: # This is an array of strings, we must free it unless it's a by_ref array
if scope == SCOPE.local or (scope == SCOPE.parameter and not local_var.byref):
if not preserve_hl:
preserve_hl = True
self.ic_exchg()
self.ic_param(gl.BOUND_TYPE, local_var.count)
self._local_array_load(scope, local_var)
self.ic_call('__ARRAYSTR_FREE_MEM', 0)
self.REQUIRES.add('arraystrfree.asm')
if local_var.class_ == CLASS.array and local_var.type_ != self.TYPE(TYPE.string) and \
(scope == SCOPE.local or (scope == SCOPE.parameter and not local_var.byref)):
if not preserve_hl:
preserve_hl = True
self.ic_exchg()
self._local_array_load(scope, local_var)
self.ic_call('__MEM_FREE', 0)
self.REQUIRES.add('free.asm')
if preserve_hl:
self.ic_exchg()
if node.convention == CONVENTION.fastcall:
self.ic_leave(CONVENTION.to_string(node.convention))
else:
self.ic_leave(node.params.size)
for bound_table in bound_tables:
self.ic_vard(bound_table.label, bound_table.data)
def visit_FUNCDECL(self, node):
""" Nested scope functions
"""
self.functions.append(node.entry)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/translator.py
|
translator.py
|
# -*- coding: utf-8 -*-
from collections import OrderedDict
from api.errmsg import syntax_error_not_constant
from api.errmsg import syntax_error_cant_convert_to_type
from api.debug import __DEBUG__
from api.errors import InvalidCONSTexpr
from api.config import OPTIONS
from api.constants import TYPE
from api.constants import SCOPE
import api.global_ as gl
from symbols.symbol_ import Symbol
from symbols.type_ import Type
from . import backend
import symbols
from api.errors import InvalidOperatorError
from .translatorinstvisitor import TranslatorInstVisitor
class TranslatorVisitor(TranslatorInstVisitor):
""" This visitor just adds the emit() method.
"""
# ------------------------------------------------
# A list of tokens that belongs to temporary
# ATTR setting
# ------------------------------------------------
ATTR = ('INK', 'PAPER', 'BRIGHT', 'FLASH', 'OVER', 'INVERSE', 'BOLD', 'ITALIC')
ATTR_TMP = tuple(x + '_TMP' for x in ATTR)
# Local flags
HAS_ATTR = False
# Previous Token
PREV_TOKEN = None
# Current Token
CURR_TOKEN = None
LOOPS = [] # Defined LOOPS
STRING_LABELS = OrderedDict()
JUMP_TABLES = []
# Type code used in DATA
DATA_TYPES = {
'str': 1,
'i8': 2,
'u8': 3,
'i16': 4,
'u16': 5,
'i32': 6,
'u32': 7,
'f16': 8,
'f': 9
}
@classmethod
def reset(cls):
cls.LOOPS = [] # Defined LOOPS
cls.STRING_LABELS = OrderedDict()
cls.JUMP_TABLES = []
def add_string_label(self, str_):
""" Maps ("folds") the given string, returning an unique label ID.
This allows several constant labels to be initialized to the same address
thus saving memory space.
:param str_: the string to map
:return: the unique label ID
"""
if self.STRING_LABELS.get(str_, None) is None:
self.STRING_LABELS[str_] = backend.tmp_label()
return self.STRING_LABELS[str_]
@property
def O_LEVEL(self):
return OPTIONS.optimization.value
@staticmethod
def TYPE(type_):
""" Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
"""
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid(type_)
return gl.SYMBOL_TABLE.basic_types[type_]
@staticmethod
def dumpMemory(MEMORY):
""" Returns a sequence of Quads
"""
for x in MEMORY:
yield str(x)
# Generic Visitor methods
def visit_BLOCK(self, node):
__DEBUG__('BLOCK', 2)
for child in node.children:
yield child
# Visits any temporal attribute
def visit_ATTR_TMP(self, node):
yield node.children[0]
self.ic_fparam(node.children[0].type_, node.children[0].t)
self.ic_call(node.token, 0) # Procedure call. Discard return
ifile = node.token.lower()
ifile = ifile[:ifile.index('_')]
backend.REQUIRES.add(ifile + '.asm')
# This function must be called before emit_strings
def emit_data_blocks(self):
if not gl.DATA_IS_USED:
return # nothing to do
for label_, datas in gl.DATAS:
self.ic_label(label_)
for d in datas:
if isinstance(d, symbols.FUNCDECL):
type_ = '%02Xh' % (self.DATA_TYPES[self.TSUFFIX(d.type_)] | 0x80)
self.ic_data(TYPE.byte_, [type_])
self.ic_data(gl.PTR_TYPE, [d.mangled])
continue
self.ic_data(TYPE.byte_, [self.DATA_TYPES[self.TSUFFIX(d.value.type_)]])
if d.value.type_ == self.TYPE(TYPE.string):
lbl = self.add_string_label(d.value.value)
self.ic_data(gl.PTR_TYPE, [lbl])
elif d.value.type_ == self.TYPE(TYPE.fixed): # Convert to bytes
bytes_ = 0xFFFFFFFF & int(d.value.value * 2 ** 16)
self.ic_data(TYPE.uinteger, ['0x%04X' % (bytes_ & 0xFFFF), '0x%04X' % (bytes_ >> 16)])
else:
self.ic_data(d.value.type_, [self.traverse_const(d.value)])
if not gl.DATAS: # The above loop was not executed, because there's no data
self.ic_label('__DATA__0')
else:
missing_data_labels = set(gl.DATA_LABELS_REQUIRED).difference([x.label.name for x in gl.DATAS])
for data_label in missing_data_labels:
self.ic_label(data_label) # A label reference by a RESTORE beyond the last DATA line
self.ic_vard('__DATA__END', ['00'])
def emit_strings(self):
for str_, label_ in self.STRING_LABELS.items():
l = '%04X' % (len(str_) & 0xFFFF) # TODO: Universalize for any arch
self.ic_vard(label_, [l] + ['%02X' % ord(x) for x in str_])
def emit_jump_tables(self):
for table_ in self.JUMP_TABLES:
self.ic_vard(table_.label, [str(len(table_.addresses))] + ['##' + x.mangled for x in table_.addresses])
def _visit(self, node):
self.norm_attr()
if isinstance(node, Symbol):
__DEBUG__('Visiting {}'.format(node.token), 1)
if node.token in self.ATTR_TMP:
return self.visit_ATTR_TMP(node)
return TranslatorInstVisitor._visit(self, node)
def norm_attr(self):
""" Normalize attr state
"""
if not self.HAS_ATTR:
return
self.HAS_ATTR = False
self.ic_call('COPY_ATTR', 0)
backend.REQUIRES.add('copy_attr.asm')
@staticmethod
def traverse_const(node):
""" Traverses a constant and returns an string
with the arithmetic expression
"""
if node.token == 'NUMBER':
return node.t
if node.token == 'UNARY':
mid = node.operator
if mid == 'MINUS':
result = ' -' + TranslatorVisitor.traverse_const(node.operand)
elif mid == 'ADDRESS':
if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'):
result = TranslatorVisitor.traverse_const(node.operand)
else:
syntax_error_not_constant(node.operand.lineno)
return
else:
raise InvalidOperatorError(mid)
return result
if node.token == 'BINARY':
mid = node.operator
if mid == 'PLUS':
mid = '+'
elif mid == 'MINUS':
mid = '-'
elif mid == 'MUL':
mid = '*'
elif mid == 'DIV':
mid = '/'
elif mid == 'MOD':
mid = '%'
elif mid == 'POW':
mid = '^'
elif mid == 'SHL':
mid = '>>'
elif mid == 'SHR':
mid = '<<'
else:
raise InvalidOperatorError(mid)
return '(%s) %s (%s)' % (TranslatorVisitor.traverse_const(node.left), mid,
TranslatorVisitor.traverse_const(node.right))
if node.token == 'TYPECAST':
if node.type_ in (Type.byte_, Type.ubyte):
return '(' + TranslatorVisitor.traverse_const(node.operand) + ') & 0xFF'
if node.type_ in (Type.integer, Type.uinteger):
return '(' + TranslatorVisitor.traverse_const(node.operand) + ') & 0xFFFF'
if node.type_ in (Type.long_, Type.ulong):
return '(' + TranslatorVisitor.traverse_const(node.operand) + ') & 0xFFFFFFFF'
if node.type_ == Type.fixed:
return '((' + TranslatorVisitor.traverse_const(node.operand) + ') & 0xFFFF) << 16'
syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_)
return
if node.token == 'VARARRAY':
return node.data_label
if node.token in ('VAR', 'LABEL', 'FUNCTION'):
# TODO: Check what happens with local vars and params
return node.t
if node.token == 'CONST':
return TranslatorVisitor.traverse_const(node.expr)
if node.token == 'ARRAYACCESS':
return '({} + {})'.format(node.entry.data_label, node.offset)
raise InvalidCONSTexpr(node)
@staticmethod
def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n]
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/translatorvisitor.py
|
translatorvisitor.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
from . import beep
from .translator import * # noqa
import api.global_
from api.constants import TYPE
__all__ = [
'beep',
]
# -----------------------------------------
# Arch initialization setup
# -----------------------------------------
api.global_.PARAM_ALIGN = 2 # Z80 param align
api.global_.BOUND_TYPE = TYPE.uinteger
api.global_.SIZE_TYPE = TYPE.ubyte
api.global_.PTR_TYPE = TYPE.uinteger
api.global_.STR_INDEX_TYPE = TYPE.uinteger
api.global_.MIN_STRSLICE_IDX = 0 # Min. string slicing position
api.global_.MAX_STRSLICE_IDX = 65534 # Max. string slicing position
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/__init__.py
|
__init__.py
|
# -*- config: utf-8 -*-
# counter for generating unique random fake values
RAND_COUNT = 0
# Labels which must start a basic block, because they're used in a JP/CALL
LABELS = {} # Label -> LabelInfo object
JUMP_LABELS = set([])
MEMORY = [] # Instructions emitted by the backend
# PROC labels name space counter
PROC_COUNTER = 0
BLOCKS = [] # Memory blocks
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/common.py
|
common.py
|
# -*- coding: utf-8 -*-
import arch
import api.utils
import api.config
from api.debug import __DEBUG__
from api.identityset import IdentitySet
from .memcell import MemCell
from .labelinfo import LabelInfo
from .helpers import ALL_REGS, END_PROGRAM_LABEL
from .common import LABELS, JUMP_LABELS
from .errors import OptimizerInvalidBasicBlockError, OptimizerError
from .cpustate import CPUState
from ..peephole import evaluator
from . import helpers
from .. import backend
class BasicBlock(object):
""" A Class describing a basic block
"""
__UNIQUE_ID = 0
clean_asm_args = False
def __init__(self, memory):
""" Initializes the internal array of instructions.
"""
self.mem = None
self.next = None # Which (if any) basic block follows this one in memory
self.prev = None # Which (if any) basic block precedes to this one in the code
self.lock = False # True if this block is being accessed by other subroutine
self.comes_from = IdentitySet() # A list/tuple containing possible jumps to this block
self.goes_to = IdentitySet() # A list/tuple of possible block to jump from here
self.modified = False # True if something has been changed during optimization
self.calls = IdentitySet()
self.label_goes = []
self.ignored = False # True if this block can be ignored (it's useless)
self.id = BasicBlock.__UNIQUE_ID
self._bytes = None
self._sizeof = None
self._max_tstates = None
self.optimized = False # True if this block was already optimized
BasicBlock.__UNIQUE_ID += 1
self.code = memory
self.cpu = CPUState()
def __len__(self):
return len(self.mem)
def __str__(self):
return '\n'.join(x for x in self.code)
def __repr__(self):
return "<{}: id: {}, len: {}>".format(self.__class__.__name__, self.id, len(self))
def __getitem__(self, key):
return self.mem[key]
def __setitem__(self, key, value):
self.mem[key].asm = value
self._bytes = None
self._sizeof = None
self._max_tstates = None
def pop(self, i):
self._bytes = None
self._sizeof = None
self._max_tstates = None
return self.mem.pop(i)
def insert(self, i, value):
memcell = MemCell(value, i)
self.mem.insert(i, memcell)
self._bytes = None
self._sizeof = None
self._max_tstates = None
@property
def code(self):
return [x.code for x in self.mem]
@code.setter
def code(self, value):
assert isinstance(value, (list, tuple))
assert all(isinstance(x, str) for x in value)
if self.clean_asm_args:
self.mem = [MemCell(helpers.simplify_asm_args(asm), i) for i, asm in enumerate(value)]
else:
self.mem = [MemCell(asm, i) for i, asm in enumerate(value)]
self._bytes = None
self._sizeof = None
self._max_tstates = None
@property
def bytes(self):
""" Returns length in bytes (number of bytes this block takes)
"""
if self._bytes is not None:
return self._bytes
self._bytes = list(x.bytes for x in self.mem)
return self._bytes
@property
def sizeof(self):
""" Returns the size of this block in bytes once assembled
"""
if self._sizeof:
return self._sizeof
self._sizeof = sum(len(x) for x in self.bytes)
return self._sizeof
@property
def max_tstates(self):
if self._max_tstates is not None:
return self._max_tstates
self._max_tstates = sum(x.max_tstates for x in self.mem)
return self._max_tstates
@property
def labels(self):
""" Returns a t-uple containing labels within this block
"""
return [cell.inst for cell in self.mem if cell.is_label]
@property
def is_partitionable(self):
""" Returns if this block can be partitions 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.code in backend.ASMS for x in self.mem[:]):
return True
for label in JUMP_LABELS:
if LABELS[label].basic_block != self:
continue
for i in range(len(self)):
if not self.mem[i].is_label:
return True # An instruction? Should start with a Jump Label
if self.mem[i].inst == label:
break # found
else:
raise OptimizerInvalidBasicBlockError(self) # Label is pointing to the wrong block? not found
return False
def update_labels(self):
""" Update global labels table so they point to the current block
"""
for l in self.labels:
LABELS[l].basic_block = self
def delete_comes_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
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
def delete_goes_to(self, basic_block):
""" Removes the basic_block ptr from the list for "goes_to"
if it exists. It also sets self.next to None if it is basic_block.
"""
if basic_block is None:
return
if self.lock:
return
self.lock = True
for i in range(len(self.goes_to)):
if self.goes_to[i] is basic_block:
self.goes_to.pop(i)
basic_block.delete_comes_from(self)
break
self.lock = False
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
def add_goes_to(self, basic_block):
""" This simulates a set. Adds the basic_block to the goes_to
list if not done already.
"""
if basic_block is None:
return
if self.lock:
return
if basic_block in self.goes_to:
return
self.lock = True
self.goes_to.add(basic_block)
basic_block.add_comes_from(self)
self.lock = False
def update_next_block(self):
""" If the last instruction of this block is a JP, JR or RET (with no
conditions) then goes_to set contains just a
single block
"""
last = self.mem[-1]
if last.inst not in {'djnz', 'jp', 'jr', 'call', 'ret', 'reti', 'retn', 'rst'}:
return
if last.inst in {'reti', 'retn'}:
if self.next is not None:
self.next.delete_comes_from(self)
return
if self.next is not None and last.condition_flag is None: # jp NNN, call NNN, rst, jr NNNN, ret
self.next.delete_comes_from(self)
if last.inst == 'ret':
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
self.add_goes_to(n_block)
def update_used_by_list(self):
""" Every label has a set containing
which blocks jumps (jp, jr, call) if any.
A block can "use" (call/jump) only another block
and only one"""
# Searches all labels and remove this block out
# of their used_by set, since this might have changed
for label in LABELS.values():
label.used_by.remove(self) # Delete this bblock
def clean_up_goes_to(self):
for x in self.goes_to:
if x is not self.next:
self.delete_goes_to(x)
def clean_up_comes_from(self):
for x in self.comes_from:
if x is not self.prev:
self.delete_comes_from(x)
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()
"""
if not len(self):
return
last = self.mem[-1]
inst = last.inst
oper = last.opers
cond = last.condition_flag
if not last.is_ender:
return
if cond is None:
self.delete_goes_to(self.next)
if last.inst in {'ret', 'reti', 'retn'} and cond is None:
return # subroutine returns are updated from CALLer blocks
if oper and oper[0]:
if oper[0] not in LABELS:
__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))
LABELS[oper[0]].used_by.add(self)
self.add_goes_to(LABELS[oper[0]].basic_block)
if inst in {'djnz', 'jp', 'jr'}:
return
assert inst in ('call', 'rst')
if self.next is None:
raise OptimizerError("Unexpected NULL next block")
final_blk = self.next # The block all the final returns should go to
stack = [LABELS[oper[0]].basic_block]
bbset = IdentitySet()
while stack:
bb = stack.pop(0)
while True:
if bb is None:
bb = DummyBasicBlock(ALL_REGS, ALL_REGS)
if bb in bbset:
break
bbset.add(bb)
if isinstance(bb, DummyBasicBlock):
bb.add_goes_to(final_blk)
break
if bb:
bb1 = bb[-1]
if bb1.inst in {'ret', 'reti', 'retn'}:
bb.add_goes_to(final_blk)
if bb1.condition_flag is None: # 'ret'
break
elif 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.append(LABELS[bb1.opers[0]].basic_block)
else:
raise OptimizerError("Unknown block label '{}'".format(bb1.opers[0]))
bb = bb.next # next contiguous block
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
if top is None:
top = len(self)
else:
top -= 1
if regs and regs[0][0] == '(' and regs[0][-1] == ')': # A memory address
r16 = helpers.single_registers(regs[0][1:-1])\
if helpers.is_16bit_oper_register(regs[0][1:-1]) else []
ix = helpers.single_registers(helpers.idx_args(regs[0][1:-1])[0]) \
if helpers.idx_args(regs[0][1:-1]) else []
rr = set(r16 + ix)
for mem in self[i:top]: # For memory accesses only mark as NOT uses if it's overwritten
if mem.inst == 'ld' and mem.opers[0] == regs[0]:
return False
if mem.opers and mem.opers[-1] == regs[0]:
return True
if rr and any(_ in r16 for _ in mem.destroys): # (hl) :: inc hl / (ix + n) :: inc ix
return True
return True
regs = api.utils.flatten_list([helpers.single_registers(x) for x in regs]) # make a copy
for ii in range(i, top):
if any(r in regs for r in self.mem[ii].requires):
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
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 helpers.is_register(regs):
regs = set(helpers.single_registers(regs))
else:
regs = set(helpers.single_registers(x) for x in regs)
return not regs.intersection(self.requires(i, end_))
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 = set()
for ii in range(i, end_):
for r in self.mem[ii].requires:
r = r.lower()
if r in regs:
result.add(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
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
def swap(self, a, b):
""" Swaps mem positions a and b
"""
self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
def goes_requires(self, regs):
""" Returns whether any of the goes_to block requires any of
the given registers.
"""
for block in self.goes_to:
if block.is_used(regs, 0):
return True
return False
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
def get_first_non_label_instruction(self):
""" Returns the memcell of the given block, which is
not a LABEL.
"""
for mem in self:
if not mem.is_label:
return mem
return None
def get_next_exec_instruction(self):
""" Return the first non label instruction to be executed, either
in this block or in the following one. If there are more than one, return None.
Also returns None if there is no instruction to be executed.
"""
result = self.get_first_non_label_instruction()
blk = self
while result is None:
if len(blk.goes_to) != 1:
return None
blk = blk.goes_to[0]
result = blk.get_first_non_label_instruction()
return result
def guesses_initial_state_from_origin_blocks(self):
""" Returns two dictionaries (regs, memory) that contains the common values
of the cpustates of all comes_from blocks
"""
if not self.comes_from:
return {}, {}
regs = self.comes_from[0].cpu.regs
mems = self.comes_from[0].cpu.mem
for blk in self.comes_from[1:]:
regs = helpers.dict_intersection(regs, blk.cpu.regs)
mems = helpers.dict_intersection(mems, blk.cpu.mem)
return regs, mems
def compute_cpu_state(self):
""" Resets and updates internal cpu state of this block
executing the instructions of the block. The block must be a basic block
(i.e. already partitioned)
"""
self.cpu.reset()
for asm_line in self.code:
self.cpu.execute(asm_line)
def optimize(self, patterns_list):
""" Tries to detect peep-hole patterns in this basic block
and remove them.
"""
if self.optimized:
return
changed = True
code = self.code
old_unary = dict(evaluator.Evaluator.UNARY)
evaluator.Evaluator.UNARY['GVAL'] = lambda x: self.cpu.get(x)
evaluator.Evaluator.UNARY['FLAGVAL'] = lambda x: {
'c': str(self.cpu.C) if self.cpu.C is not None else helpers.new_tmp_val(),
'z': str(self.cpu.Z) if self.cpu.Z is not None else helpers.new_tmp_val()
}.get(x.lower(), helpers.new_tmp_val())
if api.config.OPTIONS.optimization.value > 3:
regs, mems = self.guesses_initial_state_from_origin_blocks()
else:
regs, mems = {}, {}
while changed:
changed = False
self.cpu.reset(regs=regs, mems=mems)
for i, asm_line in enumerate(code):
for p in patterns_list:
match = p.patt.match(code[i:])
if match is None: # HINT: {} is also a valid match
continue
for var, defline in p.defines:
match[var] = defline.expr.eval(match)
evaluator.Evaluator.UNARY['IS_REQUIRED'] = lambda x: self.is_used([x], i + len(p.patt))
if not p.cond.eval(match):
continue
# all patterns applied successfully. Apply this pattern
new_code = list(code)
matched = new_code[i: i + len(p.patt)]
new_code[i: i + len(p.patt)] = p.template.filter(match)
api.errmsg.info('pattern applied [{}:{}]'.format("%03i" % p.flag, p.fname))
api.debug.__DEBUG__('matched: \n {}'.format('\n '.join(matched)), level=1)
changed = new_code != code
if changed:
code = new_code
self.code = new_code
break
if changed:
self.modified = True
break
self.cpu.execute(asm_line)
evaluator.Evaluator.UNARY.update(old_unary) # restore old copy
self.optimized = True
class DummyBasicBlock(BasicBlock):
""" A dummy basic block with some basic information
about what registers uses an destroys
"""
def __init__(self, destroys, requires):
BasicBlock.__init__(self, [])
self.__destroys = [x for x in destroys]
self.__requires = [x for x in requires]
def destroys(self):
return [x for x in self.__destroys]
def requires(self):
return [x for x in self.__requires]
def is_used(self, regs, i, top=None):
return len([x for x in regs if x in self.__requires]) > 0
def block_partition(block, i):
""" Returns two blocks, as a result of partitioning the given one at
i-th instruction.
"""
i += 1
new_block = BasicBlock([])
new_block.mem = block.mem[i:]
block.mem = block.mem[:i]
for label, lbl_info in LABELS.items():
if lbl_info.basic_block != block or lbl_info.position < len(block):
continue
lbl_info.basic_block = new_block
lbl_info.position -= len(block)
for b_ in list(block.goes_to):
block.delete_goes_to(b_)
new_block.add_goes_to(b_)
new_block.label_goes = block.label_goes
block.label_goes = []
new_block.next = block.next
new_block.prev = block
block.next = new_block
new_block.add_comes_from(block)
if new_block.next is not None:
new_block.next.prev = new_block
if block in new_block.next.comes_from:
new_block.next.delete_comes_from(block)
new_block.next.add_comes_from(new_block)
block.update_next_block()
return block, new_block
def get_basic_blocks(block):
""" If a block is not partitionable, returns a list with the same block.
Otherwise, returns a list with the resulting blocks, recursively.
"""
result = []
EDP = END_PROGRAM_LABEL + ':'
new_block = block
while new_block:
block = new_block
new_block = None
for i, mem in enumerate(block):
if i and mem.code == EDP: # END_PROGRAM label always starts a basic block
block, new_block = block_partition(block, i - 1)
LABELS[END_PROGRAM_LABEL].basic_block = new_block
break
if mem.is_ender:
block, new_block = block_partition(block, i)
if not mem.condition_flag:
block.delete_goes_to(new_block)
for l in mem.opers:
if l in LABELS:
JUMP_LABELS.add(l)
block.label_goes.append(l)
break
if mem.is_label and mem.code[:-1] not in LABELS:
raise OptimizerError("Missing label '{}' in labels list".format(mem.code[:-1]))
if mem.code in arch.zx48k.backend.ASMS: # An inline ASM block
block, new_block = block_partition(block, max(0, i - 1))
break
result.append(block)
for label in JUMP_LABELS:
blk = LABELS[label].basic_block
if isinstance(blk, DummyBasicBlock):
continue
must_partition = False
# This label must point to the beginning of blk, just before the code
# Otherwise we must partition it (must_partition = True)
for i, cell in enumerate(blk):
if cell.inst == label:
break # already starts with this label
if cell.is_label:
continue # It's another label
if cell.is_ender:
raise OptimizerInvalidBasicBlockError(blk)
must_partition = True
else:
__DEBUG__("Label {} not found in BasicBlock {}".format(label, blk.id))
continue
if must_partition:
j = result.index(blk)
block_, new_block_ = block_partition(blk, i - 1)
LABELS[label].basic_block = new_block_
result.pop(j)
result.insert(j, block_)
result.insert(j + 1, new_block_)
for b in result:
b.update_goes_and_comes()
return result
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/basicblock.py
|
basicblock.py
|
# -*- coding: utf-8 -*-
from api.identityset import IdentitySet
from . import common
from . import errors
class LabelInfo(object):
""" Class describing label information
"""
def __init__(self, label, addr, basic_block=None, position=0):
""" Stores the label name, the address counter into memory (rather useless)
and which basic block contains it.
"""
self.label = label
self.addr = addr
self.basic_block = basic_block
self.position = position # Position within the block
self.used_by = IdentitySet() # Which BB uses this label, if any
if label in common.LABELS.keys():
raise errors.DuplicatedLabelError(label)
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/labelinfo.py
|
labelinfo.py
|
import re
from .patterns import RE_OUTC, RE_INDIR16
from .helpers import single_registers
from libzxbasm import z80
# Dict of patterns to normalized instructions. I.e. 'ld a, 5' -> 'LD A,N'
Z80_PATTERN = {}
class Asm(object):
""" Defines an asm instruction
"""
def __init__(self, asm):
assert isinstance(asm, str)
asm = asm.strip()
assert asm, "Empty instruction '{}'".format(asm)
self.inst = Asm.inst(asm)
self.oper = Asm.opers(asm)
self.asm = '{} {}'.format(self.inst, ' '.join(asm.split(' ', 1)[1:])).strip()
self.cond = Asm.condition(asm)
self.output = Asm.result(asm)
self._bytes = None
self._max_tstates = None
self.is_label = self.inst[-1] == ':'
def _compute_bytes(self):
for patt, opcode_data in Z80_PATTERN.items():
if patt.match(self.asm):
self._bytes = tuple(opcode_data.opcode.split())
self._max_tstates = opcode_data.T
return
self._bytes = tuple()
self._max_tstates = 0
@property
def bytes(self):
""" Returns the assembled bytes as a list of hexadecimal ones.
Unknown bytes will be returned as 'XX'. e.g.:
'ld a, 5' => ['3D', 'XX']
Labels will return [] as they have no bytes
"""
if self._bytes is None:
self._compute_bytes()
return self._bytes
@property
def max_tstates(self):
""" Returns the max number of t-states this instruction takes to
execute (conditional jumps have two possible values, returns the
maximum)
"""
if self._max_tstates is None:
self._compute_bytes()
return self._max_tstates
@staticmethod
def inst(asm):
tmp = asm.strip(' \t\n').split(' ', 1)[0]
return tmp.lower() if tmp.upper() in z80.Z80INSTR else tmp
@staticmethod
def opers(inst):
""" Returns operands of an ASM instruction.
Even "indirect" operands, like SP if RET or CALL is used.
"""
i = inst.strip(' \t\n').split(' ', 1)
I = i[0].lower() # Instruction
i = ''.join(i[1:])
op = [x.strip() for x in i.split(',')]
if I in {'call', 'jp', 'jr'} and len(op) > 1:
op = op[1:] + ['f']
elif I == 'djnz':
op.append('b')
elif I in {'push', 'pop', 'call'}:
op.append('sp') # Sp is also affected by push, pop and call
elif I in {'or', 'and', 'xor', 'neg', 'cpl', 'rrca', 'rlca'}:
op.append('a')
elif I in {'rra', 'rla'}:
op.extend(['a', 'f'])
elif I in ('rr', 'rl'):
op.append('f')
elif I in {'adc', 'sbc'}:
if len(op) == 1:
op = ['a', 'f'] + op
elif I in {'add', 'sub'}:
if len(op) == 1:
op = ['a'] + op
elif I in {'ldd', 'ldi', 'lddr', 'ldir'}:
op = ['hl', 'de', 'bc']
elif I in {'cpd', 'cpi', 'cpdr', 'cpir'}:
op = ['a', 'hl', 'bc']
elif I == 'exx':
op = ['*', 'bc', 'de', 'hl', 'b', 'c', 'd', 'e', 'h', 'l']
elif I in {'ret', 'reti', 'retn'}:
op += ['sp']
elif I == 'out':
if len(op) and RE_OUTC.match(op[0]):
op[0] = 'c'
else:
op.pop(0)
elif I == 'in':
if len(op) > 1 and RE_OUTC.match(op[1]):
op[1] = 'c'
else:
op.pop(1)
for i in range(len(op)):
tmp = RE_INDIR16.match(op[i])
if tmp is not None:
op[i] = '(' + op[i].strip()[1:-1].strip().lower() + ')' # ' ( dE ) ' => '(de)'
return op
@staticmethod
def condition(asm):
""" Returns the flag this instruction uses
or None. E.g. 'c' for Carry, 'nz' for not-zero, etc.
That is the condition required for this instruction
to execute. For example: ADC A, 0 does NOT have a
condition flag (it always execute) whilst RET C does.
DJNZ has condition flag NZ
"""
i = Asm.inst(asm)
if i not in {'call', 'jp', 'jr', 'ret', 'djnz'}:
return None # This instruction always execute
if i == 'ret':
asm = [x.lower() for x in asm.split(' ') if x != '']
return asm[1] if len(asm) > 1 else None
if i == 'djnz':
return 'nz'
asm = [x.strip() for x in asm.split(',')]
asm = [x.lower() for x in asm[0].split(' ') if x != '']
if len(asm) > 1 and asm[1] in {'c', 'nc', 'z', 'nz', 'po', 'pe', 'p', 'm'}:
return asm[1]
return None
@staticmethod
def result(asm):
""" Returns which 8-bit registers (and SP for INC SP, DEC SP, etc.) are used by an asm
instruction to return a result.
"""
ins = Asm.inst(asm)
op = Asm.opers(asm)
if ins in ('or', 'and') and op == ['a']:
return ['f']
if ins in {'xor', 'or', 'and', 'neg', 'cpl', 'daa', 'rld', 'rrd', 'rra', 'rla', 'rrca', 'rlca'}:
return ['a', 'f']
if ins in {'bit', 'cp', 'scf', 'ccf'}:
return ['f']
if ins in {'sub', 'add', 'sbc', 'adc'}:
if len(op) == 1:
return ['a', 'f']
else:
return single_registers(op[0]) + ['f']
if ins == 'djnz':
return ['b', 'f']
if ins in {'ldir', 'ldi', 'lddr', 'ldd'}:
return ['f', 'b', 'c', 'd', 'e', 'h', 'l']
if ins in {'cpi', 'cpir', 'cpd', 'cpdr'}:
return ['f', 'b', 'c', 'h', 'l']
if ins in ('pop', 'ld'):
return single_registers(op[0])
if ins in {'inc', 'dec', 'sbc', 'rr', 'rl', 'rrc', 'rlc'}:
return ['f'] + single_registers(op[0])
if ins in ('set', 'res'):
return single_registers(op[1])
return []
def __len__(self):
return len(self.asm) > 0
def init():
""" Initializes table of regexp -> dict entry
"""
def make_patt(mnemo):
""" Given a mnemonic returns it's pattern tu match it
"""
return r'^[ \t]*{}[ \t]*$'.format(RE_.sub('.+', re.escape(mnemo).replace(',', r',[ \t]*')))
RE_ = re.compile(r'\bN+\b')
for mnemo, opcode_data in z80.Z80SET.items():
pattern = make_patt(mnemo)
Z80_PATTERN[re.compile(pattern, flags=re.IGNORECASE)] = opcode_data
Z80_PATTERN[re.compile(make_patt('DEFB NN'), flags=re.IGNORECASE)] = z80.Opcode('DEFB NN', 0, 1, 'XX')
Z80_PATTERN[re.compile(make_patt('DEFW NNNN'), flags=re.IGNORECASE)] = z80.Opcode('DEFW NNNN', 0, 2, 'XX XX')
init()
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/asm.py
|
asm.py
|
# -*- coding: utf-8 -*-
from api.errors import Error
class DuplicatedLabelError(Error):
""" Exception raised when a duplicated Label is found.
This should never happen.
"""
def __init__(self, label):
Error.__init__(self, "Duplicated label '{}'".format(label))
self.label = label
class OptimizerError(Error):
""" Generic exception raised during the optimization phase
"""
def __init__(self, msg):
Error.__init__(self, msg)
class OptimizerInvalidBasicBlockError(OptimizerError):
""" Exception raised when a block is not correctly partitioned.
This should never happen.
"""
def __init__(self, block):
Error.__init__(self, "Invalid block '{}'".format(block.id))
self.block = block
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/errors.py
|
errors.py
|
# -*- coding: utf-8 -*-
import re
from . import patterns
from . import common
# All 'single' registers (even f FLAG one). SP is not decomposable so it's 'single' already
ALL_REGS = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l',
'ixh', 'ixl', 'iyh', 'iyl', 'r', 'i', 'sp'}
# The set of all registers as they can appear in any instruction as operands
REGS_OPER_SET = {'a', 'b', 'c', 'd', 'e', 'h', 'l',
'bc', 'de', 'hl', 'sp', 'ix', 'iy', 'ixh', 'ixl', 'iyh', 'iyl',
'af', "af'", 'i', 'r'}
# Instructions that marks the end of a basic block (any branching instruction)
BLOCK_ENDERS = {'jr', 'jp', 'call', 'ret', 'reti', 'retn', 'djnz', 'rst'}
UNKNOWN_PREFIX = '*UNKNOWN_'
END_PROGRAM_LABEL = '__END_PROGRAM' # Label for end program
RE_UNK_PREFIX = re.compile('^' + re.escape(UNKNOWN_PREFIX) + r'\d+$')
HL_SEP = '|' # Hi/Low separator
def new_tmp_val():
""" Generates an 8-bit unknown value
"""
common.RAND_COUNT += 1
return '{0}{1}'.format(UNKNOWN_PREFIX, common.RAND_COUNT)
def new_tmp_val16():
""" Generates an unknown 16-bit tmp value concatenating two 8-it unknown ones
"""
return '{}{}{}'.format(new_tmp_val(), HL_SEP, new_tmp_val())
def is_unknown(x):
if x is None:
return True
if isinstance(x, int):
return False
assert isinstance(x, str)
xx = x.split(HL_SEP)
if len(xx) > 2:
return False
return any(RE_UNK_PREFIX.match(_) for _ in xx)
def is_unknown8(x):
if x is None:
return True
if not is_unknown(x):
return False
return len(x.split(HL_SEP)) == 1
def is_unknown16(x):
if x is None:
return True
if not is_unknown(x):
return False
return len(x.split(HL_SEP)) == 2
def get_L_from_unknown_value(tmp_val):
""" Given a 16bit *UNKNOWN value, returns it's lower part, which is the same 2nd part,
after splitting by HL_SEP. If the parameter is None, a new tmp_value will be generated.
If the value is a composed one (xxxH | yyyL) returns yyyL.
"""
assert is_unknown(tmp_val), "Malformed unknown value '{}'".format(tmp_val)
if tmp_val is None:
tmp_val = new_tmp_val16()
return tmp_val.split(HL_SEP)[-1]
def get_H_from_unknown_value(tmp_val):
""" Given a 16bit *UNKNOWN value, returns it's higher part, which is the same 1st part,
after splitting by HL_SEP. If the parameter is None, a new tmp_value will be generated.
If the value is a composed one (xxxH | yyyL) returns yyyH.
"""
assert is_unknown(tmp_val), "Malformed unknown value '{}'".format(tmp_val)
if tmp_val is None:
tmp_val = new_tmp_val16()
return tmp_val.split(HL_SEP)[0]
def is_mem_access(arg):
""" Returns if a given string is a memory access, that is
if it matches the form (...)
"""
arg = arg.strip()
return (arg[0], arg[-1]) == ('(', ')')
# TODO: to be rewritten
def is_number(x):
""" Returns whether X """
if x is None or x == '':
return False
if isinstance(x, (int, float)):
return True
if isinstance(x, str):
x = x.strip()
if isinstance(x, str) and is_mem_access(x):
return False
try:
tmp = eval(x, {}, {})
if isinstance(tmp, (int, float)):
return True
except NameError:
pass
except SyntaxError:
pass
except ValueError:
pass
return patterns.RE_NUMBER.match(str(x)) is not None
def valnum(x):
""" If x is a numeric value (int, float) or it's a string
representation of a number (hexa, binary), returns it numeric value.
Otherwise returns None
"""
if not is_number(x):
return None
x = str(x)
if x[0] == '%':
return int(x[1:], 2)
if x[-1] in ('b', 'B'):
return int(x[:-1], 2)
if x[0] == '$':
return int(x[1:], 16)
if x[-1] in ('h', 'H'):
return int(x[:-1], 16)
return int(eval(x, {}, {}))
def simplify_arg(arg):
""" Given an asm operand (str), if it can be evaluated to a single 16 bit integer number it will be done so.
Memory addresses will preserve their parenthesis. If the string can not be simplified, it will be
returned as is.
eg.:
0 -> 0
(0) -> (0)
0 + 3 -> 3
(3 + 1) -> (4)
(a - 1) -> (a - 1)
b - 5 -> b - 5
This is very simple "parsing" (for speed) and it won't understand (5) + (6) and will be returned as (11)
"""
result = None
arg = arg.strip()
try:
tmp = eval(arg, {}, {})
if isinstance(tmp, (int, float)):
result = str(tmp)
except NameError:
pass
except SyntaxError:
pass
except ValueError:
pass
if result is None:
return arg
if not is_mem_access(arg):
return result
return '({})'.format(result)
def simplify_asm_args(asm):
""" Given an asm instruction try to simplify its args.
"""
chunks = [x for x in asm.split(' ', 1)]
if len(chunks) != 2:
return asm
args = [simplify_arg(x) for x in chunks[1].split(',', 1)]
return '{} {}'.format(chunks[0], ', '.join(args))
def is_register(x):
""" True if x is a register.
"""
if not isinstance(x, str):
return False
return x.lower() in REGS_OPER_SET
def is_8bit_normal_register(x):
""" Returns whether the given string x is a "normal" 8 bit register. Those are 8 bit registers
which belongs to the normal (documented) Z80 instruction set as operands (so a', f', ixh, etc
are excluded).
"""
return x.lower() in {'a', 'b', 'c', 'd', 'e', 'i', 'h', 'l'}
def is_8bit_idx_register(x):
""" Returns whether the given string x one of the undocumented IX, IY 8 bit registers.
"""
return x.lower() in {'ixh', 'ixl', 'iyh', 'iyl'}
def is_8bit_oper_register(x):
""" Returns whether the given string x is an 8 bit register that can be used as an
instruction operand. This included those of the undocumented Z80 instruction set as
operands (ixh, ixl, etc) but not h', f'.
"""
return x.lower() in {'a', 'b', 'c', 'd', 'e', 'i', 'h', 'l', 'ixh', 'ixl', 'iyh', 'iyl'}
def is_16bit_normal_register(x):
""" Returns whether the given string x is a "normal" 16 bit register. Those are 16 bit registers
which belongs to the normal (documented) Z80 instruction set as operands which can be operated
directly (i.e. load a value directly), and not for indexation (IX + n, for example).
So af, ix, iy, sp, bc', hl', de' are excluded.
"""
return x.lower() in {'bc', 'de', 'hl'}
def is_16bit_idx_register(x):
""" Returns whether the given string x is a indexable (i.e. IX + n) 16 bit register.
"""
return x.lower() in {'ix', 'iy'}
def is_16bit_composed_register(x):
""" A 16bit register that can be decomposed into a high H16 and low L16 part
"""
return x.lower() in {'af', "af'", 'bc', 'de', 'hl', 'ix', 'iy'}
def is_16bit_oper_register(x):
""" Returns whether the given string x is a 16 bit register. These are any 16 bit register
which belongs to the normal (documented) Z80 instruction set as operands.
"""
return x.lower() in {'af', "af'", 'bc', 'de', 'hl', 'ix', 'iy', 'sp'}
def LO16(x):
""" Given a 16-bit register (lowercase string), returns the low 8 bit register of it.
The string *must* be a 16 bit lowercase register. SP register is not "decomposable" as
two 8-bit registers and this is considered an error.
"""
x = x.lower()
assert is_16bit_oper_register(x), "'%s' is not a 16bit register" % x
assert x != 'sp', "'sp' register cannot be split into two 8 bit registers"
if is_16bit_idx_register(x):
return x + 'l'
return x[1] + ("'" if "'" in x else '')
def HI16(x):
""" Given a 16-bit register (lowercase string), returns the high 8 bit register of it.
The string *must* be a 16 bit lowercase register. SP register is not "decomposable" as
two 8-bit registers and this is considered an error.
"""
x = x.lower()
assert is_16bit_oper_register(x), "'%s' is not a 16bit register" % x
assert x != 'sp', "'sp' register cannot be split into two 8 bit registers"
if is_16bit_idx_register(x):
return x + 'h'
return x[0] + ("'" if "'" in x else '')
def single_registers(op):
""" Given an iterable (set, list) of registers like ['a', 'bc', "af'", 'h', 'hl'] returns
a list of single registers: ['a', "a'", "f'", 'b', 'c', 'h', 'l'].
Non register parameters (like numbers) will be ignored.
Notes:
- SP register will be returned as is since it's not decomposable in two 8 bit registers.
- IX and IY will be returned as {'ixh', 'ixl'} and {'iyh', 'iyl'} respectively
"""
result = set()
if not isinstance(op, (list, set)):
op = [op]
for x in op:
if is_8bit_oper_register(x) or x.lower() in ('f', 'sp'):
result.add(x)
elif not is_16bit_oper_register(x):
continue
else: # Must be a 16bit reg or we have an internal error!
result = result.union([LO16(x), HI16(x)])
return sorted(result)
def idx_args(x):
""" Given an argument x (string), returns None if it's not an index operation "ix/iy + n"
Otherwise return a tuple (reg, oper, offset). It's case insensitive and the register is always returned
in lowercase.
Notice the parenthesis must NOT be included. So '(ix + 5)' won't match, whilst 'ix + 5' will.
For example:
- 'ix + 3' => ('ix', '+', '3')
- 'IY - Something + 4' => ('iy', '-', 'Something + 4')
"""
match = patterns.RE_IDX.match(x)
if match is None:
return None
reg, sign, args = match.groups()
return reg.lower(), sign, args
def LO16_val(x):
""" Given an x value, it must be None, unknown, or an integer.
Then returns it lower part. If it's none, a new tmp will be returned.
"""
if x is None:
return new_tmp_val()
if valnum(x) is not None:
return str(int(x) & 0xFF)
if not is_unknown(x):
return new_tmp_val()
return x.split(HL_SEP)[-1]
def HI16_val(x):
""" Given an x value, it must be None, unknown, or an integer.
Then returns it upper part. If it's None, a new tmp will be returned.
It it's an unknown8, return 0, because it's considered an 8 bit value.
"""
if x is None:
return new_tmp_val()
if valnum(x) is not None:
return str((int(x) >> 8) & 0xFF)
if not is_unknown(x):
return new_tmp_val()
return "0{}{}".format(HL_SEP, x).split(HL_SEP)[-2]
def dict_intersection(dict_a, dict_b):
""" Given 2 dictionaries a, b, returns a new one which contains the common key/pair values.
e.g. for {'a': 1, 'b': 'x'}, {'a': 'q', 'b': 'x', 'c': 2} returns {'b': 'x'}
:param dict_a: a python dictionary (or compatible class instance)
:param dict_b: a python dictionary (or compatible class instance)
:return a python dictionary with the key/val intersection
"""
return {k: v for k, v in dict_a.items() if k in dict_b and dict_b[k] == v}
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/helpers.py
|
helpers.py
|
# -*- coding: utf-8 -*-
import re
__doc__ = """ Patterns to match against generated ASM code.
"""
# matches an integer in signed decimal, hexadecimal ($XXXX, or XXXXh) or binary (nnnnB)
RE_NUMBER = re.compile(r'^([-+]?[0-9]+|$[A-Fa-f0-9]+|[0-9][A-Fa-f0-9]*[Hh]|%[01]+|[01]+[bB])$')
# matches an indexed register operand like (IX + 3) or (iy - 4). Case insensitive
RE_INDIR_OPER = re.compile(r'\([ \t]*[Ii][XxYy][ \t]*[-+][ \t]*[0-9]+[ \t]*\)')
# captures the offset of the indexed register operand. ie (ix+5) => +, 5
RE_IXIND_OPER = re.compile(r'[iI][xXyY][ \t]*([-+])(?:[ \t]*)([0-9]+)?')
# captures the register, the operator and the operand
RE_IDX = re.compile(r'^([iI][xXyY])[ ]*([-+])[ \t]*(.*)$')
# captures a label definition (simply an identifier ending with a colon)
RE_LABEL = re.compile(r'^[ \t]*[_a-zA-Z][a-zA-Z\d]*:')
# matches and captures (de) or (hl)
RE_INDIR16 = re.compile(r'[ \t]*\([ \t]*([dD][eE]|[hH][lL])[ \t]*\)[ \t]*')
# matches the '(c)' register in instruction out (c), ...
RE_OUTC = re.compile(r'[ \t]*\([ \t]*[cC]\)')
# matches an identifier
RE_ID = re.compile(r'[.a-zA-Z_][.a-zA-Z_0-9]*')
# matches a pragma line
RE_PRAGMA = re.compile(r'^#[ \t]?pragma[ \t]opt[ \t]')
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/patterns.py
|
patterns.py
|
# -*- coding: utf-8 -*-
from api.utils import flatten_list
from arch.zx48k.peephole import engine
from .patterns import RE_PRAGMA, RE_LABEL
from .common import LABELS, JUMP_LABELS, MEMORY
from .helpers import END_PROGRAM_LABEL, ALL_REGS
from .basicblock import DummyBasicBlock
from . import basicblock
from .labelinfo import LabelInfo
from api.config import OPTIONS
from api.debug import __DEBUG__
def init():
global LABELS
global JUMP_LABELS
LABELS.clear()
JUMP_LABELS.clear()
LABELS['*START*'] = LabelInfo('*START*', 0, DummyBasicBlock(ALL_REGS, ALL_REGS)) # Special START BLOCK
LABELS['*__END_PROGRAM*'] = LabelInfo('__END_PROGRAM', 0, DummyBasicBlock(ALL_REGS, list('bc')))
# SOME Global modules initialization
LABELS['__ADDF'] = LabelInfo('__ADDF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__SUBF'] = LabelInfo('__SUBF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__DIVF'] = LabelInfo('__DIVF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__MULF'] = LabelInfo('__MULF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__GEF'] = LabelInfo('__GEF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__GTF'] = LabelInfo('__GTF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__EQF'] = LabelInfo('__EQF', 0, DummyBasicBlock(ALL_REGS, list('aedbc')))
LABELS['__STOREF'] = LabelInfo('__STOREF', 0, DummyBasicBlock(ALL_REGS, list('hlaedbc')))
LABELS['PRINT_AT'] = LabelInfo('PRINT_AT', 0, DummyBasicBlock(ALL_REGS, list('a')))
LABELS['INK'] = LabelInfo('INK', 0, DummyBasicBlock(ALL_REGS, list('a')))
LABELS['INK_TMP'] = LabelInfo('INK_TMP', 0, DummyBasicBlock(ALL_REGS, list('a')))
LABELS['PAPER'] = LabelInfo('PAPER', 0, DummyBasicBlock(ALL_REGS, list('a')))
LABELS['PAPER_TMP'] = LabelInfo('PAPER_TMP', 0, DummyBasicBlock(ALL_REGS, list('a')))
LABELS['RND'] = LabelInfo('RND', 0, DummyBasicBlock(ALL_REGS, []))
LABELS['INKEY'] = LabelInfo('INKEY', 0, DummyBasicBlock(ALL_REGS, []))
LABELS['PLOT'] = LabelInfo('PLOT', 0, DummyBasicBlock(ALL_REGS, ['a']))
LABELS['DRAW'] = LabelInfo('DRAW', 0, DummyBasicBlock(ALL_REGS, ['h', 'l']))
LABELS['DRAW3'] = LabelInfo('DRAW3', 0, DummyBasicBlock(ALL_REGS, list('abcde')))
LABELS['__ARRAY'] = LabelInfo('__ARRAY', 0, DummyBasicBlock(ALL_REGS, ['h', 'l']))
LABELS['__MEMCPY'] = LabelInfo('__MEMCPY', 0, DummyBasicBlock(list('bcdefhl'), list('bcdehl')))
LABELS['__PLOADF'] = LabelInfo('__PLOADF', 0, DummyBasicBlock(ALL_REGS, ALL_REGS)) # Special START BLOCK
LABELS['__PSTOREF'] = LabelInfo('__PSTOREF', 0, DummyBasicBlock(ALL_REGS, ALL_REGS)) # Special START BLOCK
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
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.asm
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.asm[0] == ';':
MEMORY.pop(i)
block.mem = MEMORY
block.asm = [x.asm for x in MEMORY if len(x.asm)]
def get_labels(basic_block):
""" Traverses memory, to annotate all the labels in the global
LABELS table
"""
for i, cell in enumerate(basic_block):
if cell.is_label:
label = cell.inst
LABELS[label] = LabelInfo(label, cell.addr, basic_block, i) # Stores it globally
def initialize_memory(basic_block):
""" Initializes global memory array with the one in the main (initial) basic_block
"""
global MEMORY
init()
MEMORY = basic_block.mem
get_labels(basic_block)
def optimize(initial_memory):
""" This will remove useless instructions
"""
global BLOCKS
global PROC_COUNTER
del MEMORY[:]
PROC_COUNTER = 0
cleanupmem(initial_memory)
if OPTIONS.optimization.value <= 2: # if -O2 or lower, do nothing and return
return '\n'.join(x for x in initial_memory if not RE_PRAGMA.match(x))
basicblock.BasicBlock.clean_asm_args = OPTIONS.optimization.value > 3
bb = basicblock.BasicBlock(initial_memory)
cleanup_local_labels(bb)
initialize_memory(bb)
BLOCKS = basic_blocks = basicblock.get_basic_blocks(bb) # 1st partition the Basic Blocks
for b in basic_blocks:
__DEBUG__('--- BASIC BLOCK: {} ---'.format(b.id), 1)
__DEBUG__('Code:\n' + '\n'.join(' {}'.format(x) for x in b.code), 1)
__DEBUG__('Requires: {}'.format(b.requires()), 1)
__DEBUG__('Destroys: {}'.format(b.destroys()), 1)
__DEBUG__('Label goes: {}'.format(b.label_goes), 1)
__DEBUG__('Comes from: {}'.format([x.id for x in b.comes_from]), 1)
__DEBUG__('Goes to: {}'.format([x.id for x in b.goes_to]), 1)
__DEBUG__('Next: {}'.format(b.next.id if b.next is not None else None), 1)
__DEBUG__('Size: {} Time: {}'.format(b.sizeof, b.max_tstates), 1)
__DEBUG__('--- END ---', 1)
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)
# In O3 we simplify the graph by reducing jumps over jumps
for label in JUMP_LABELS:
block = LABELS[label].basic_block
if isinstance(block, DummyBasicBlock):
continue
# The instruction that starts this block must be one of jr / jp
first = block.get_next_exec_instruction()
if first is None or first.inst not in ('jp', 'jr'):
continue
for blk in list(LABELS[label].used_by):
if not first.condition_flag or blk[-1].condition_flag == first.condition_flag:
new_label = first.opers[0]
blk[-1].asm = blk[-1].code.replace(label, new_label)
block.delete_comes_from(blk)
LABELS[label].used_by.remove(blk)
LABELS[new_label].used_by.add(blk)
blk.add_goes_to(LABELS[new_label].basic_block)
for x in basic_blocks:
x.compute_cpu_state()
filtered_patterns_list = [p for p in engine.PATTERNS if OPTIONS.optimization.value >= p.level >= 3]
for x in basic_blocks:
x.optimize(filtered_patterns_list)
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.code for x in basic_blocks if not x.ignored])
if not RE_PRAGMA.match(y)])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/__init__.py
|
__init__.py
|
# -*- coding: utf-8 -*-
import re
from . import helpers
from .. import backend
from .asm import Asm
from api.utils import flatten_list
from libzxbasm import asmlex
class MemCell(object):
""" Class describing a memory address.
It just contains the addr (memory array index), and
the instruction.
"""
def __init__(self, instr, addr):
self.addr = addr
self.__instr = None
self.asm = instr
@property
def asm(self):
return self.__instr
@asm.setter
def asm(self, value):
self.__instr = Asm(value)
@property
def code(self):
return self.asm.asm
def __str__(self):
return self.asm.asm
def __repr__(self):
return '{0}:{1}'.format(self.addr, str(self))
def __len__(self):
return len(self.asm)
@property
def bytes(self):
""" Bytes (unresolved) to compose this instruction
"""
return self.asm.bytes
@property
def sizeof(self):
""" Size in bytes of this cell
"""
return len(self.bytes)
@property
def max_tstates(self):
""" Max number of t-states (time) this cell takes
"""
return self.asm.max_tstates
@property
def is_label(self):
""" Returns whether the current addr
contains a label.
"""
return self.asm.is_label
@property
def is_ender(self):
""" Returns if this instruction is a BLOCK ender
"""
return self.inst in helpers.BLOCK_ENDERS
@property
def inst(self):
""" Returns just the asm instruction in lower
case. E.g. 'ld', 'jp', 'pop'
"""
if self.is_label:
return self.asm.asm[:-1]
return self.asm.inst
@property
def condition_flag(self):
""" Returns the flag this instruction uses
or None. E.g. 'c' for Carry, 'nz' for not-zero, etc.
That is the condition required for this instruction
to execute. For example: ADC A, 0 does NOT have a
condition flag (it always execute) whilst RETC does.
"""
return self.asm.cond
@property
def opers(self):
""" Returns a list of operands (i.e. register) this mnemonic uses
"""
return self.asm.oper
@property
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.code in backend.ASMS:
return helpers.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', helpers.single_registers(o[:1]))
elif i in {'ldir', 'lddr'}:
res.update('b', 'c', 'd', 'e', 'h', 'l', 'f')
elif i in {'ldd', 'ldi'}:
res.update('b', 'c', 'd', 'e', 'h', 'l', '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(helpers.single_registers(o[:1]))
elif i in ('inc', 'dec'):
res.update('f', helpers.single_registers(o[:1]))
elif i == 'exx':
res.update('b', 'c', 'd', 'e', 'h', 'l')
elif i == 'ex':
res.update(helpers.single_registers(o[0]))
res.update(helpers.single_registers(o[1]))
elif i in {'ccf', 'scf', 'bit', 'cp'}:
res.add('f')
elif i in {'or', 'and'}:
res.add('f')
if o[0] != 'a':
res.add('a')
elif i in {'xor', 'add', 'adc', 'sub', 'sbc'}:
if len(o) > 1:
res.update(helpers.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(helpers.single_registers(o[0]))
res.add('f')
elif i in ('set', 'res'):
res.update(helpers.single_registers(o[1]))
return res
@property
def requires(self):
""" Returns the registers, operands, etc. required by an instruction.
"""
if self.code in backend.ASMS:
return helpers.ALL_REGS
if self.inst == '#pragma':
tmp = self.code.split(' ')[1:]
if tmp[0] != 'opt':
return
if tmp[1] == 'require':
return set(flatten_list([helpers.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 helpers.is_number(o[0]):
result = result.union(helpers.single_registers(o))
elif i in ['or', 'and']:
# AND A, and OR A do need the a register to compute Z flag
result.add('a')
if o[0][0] != '(' and not helpers.is_number(o[0]):
result = result.union(helpers.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 helpers.is_number(o[0]):
result = result.union(helpers.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(helpers.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(helpers.single_registers(o) + ['f'])
elif i in {'sla', 'sll', 'sra', 'srl', 'inc', 'dec'}:
result = result.union(helpers.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 helpers.is_number(o[1]):
result = result.union(helpers.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(helpers.single_registers(o))
elif i in {'bit', 'set', 'res'}:
result = result.union(helpers.single_registers(o[1]))
elif i == 'out':
result.add(o[1])
if o[0] == 'c':
result.update('b', 'c')
elif i == 'in':
if o[1] == 'c':
result.update('b', 'c')
elif i == 'im':
result.add('i')
return result
def affects(self, reglist):
""" Returns if this instruction affects any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = helpers.single_registers(reglist)
return len([x for x in self.destroys if x in reglist]) > 0
def needs(self, reglist):
""" Returns if this instruction need any of the registers
in reglist.
"""
if isinstance(reglist, str):
reglist = [reglist]
reglist = helpers.single_registers(reglist)
return len([x for x in self.requires if x in reglist]) > 0
@property
def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.asm
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 BaseException:
pass
return result
def replace_label(self, old_label, new_label):
""" Replaces old label with a new one
"""
if old_label == new_label:
return
tmp = re.compile(r'\b' + old_label + r'\b')
last = 0
l = len(new_label)
while True:
match = tmp.search(self.asm[last:])
if not match:
break
txt = self.asm
self.asm = txt[:last + match.start()] + new_label + txt[last + match.end():]
last += match.start() + l
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/memcell.py
|
memcell.py
|
# -*- coding: utf-8 -*-
from collections import defaultdict
from . import asm
from .helpers import new_tmp_val, new_tmp_val16, HI16, LO16, HL_SEP
from .helpers import is_unknown, is_unknown16, valnum, is_number
from .helpers import is_register, is_8bit_oper_register, is_16bit_composed_register
from .helpers import get_L_from_unknown_value, idx_args, LO16_val
class Flags(object):
def __init__(self):
self.C = None
self.Z = None
self.P = None
self.S = None
class CPUState(object):
""" A class storing registers value information (CPU State).
"""
def __init__(self):
self.regs = None
self.stack = None
self.mem = None
self._flags = None
self._16bit = None
self.reset()
@property
def Z(self):
""" The Z flag
"""
return self._flags[0].Z
@Z.setter
def Z(self, val):
""" Sets the Z flag, and tries to update the F register accordingly.
If the F register is unknown, sets it with a new unknown value.
"""
assert is_unknown(val) or val in (0, 1)
self._flags[0].Z = val
if not is_unknown(val) and is_number(self.regs['f']):
self.regs['f'] = str((self.getv('f') & 0xBF) | (val << 6))
else:
self.regs['f'] = new_tmp_val()
@property
def C(self):
""" The C flag
"""
return self._flags[0].C
@C.setter
def C(self, val):
""" Sets the C flag, and tries to update the F register accordingly.
If the F register is unknown, sets it with a new unknown value.
"""
assert is_unknown(val) or val in (0, 1)
self._flags[0].C = val
if not is_unknown(val) and is_number(self.regs['f']):
self.regs['f'] = str((self.getv('f') & 0xFE) | val)
else:
self.regs['f'] = new_tmp_val()
@property
def P(self):
""" The P flag
"""
return self._flags[0].P
@P.setter
def P(self, val):
""" Sets the P flag, and tries to update the F register accordingly.
If the F register is unknown, sets it with a new unknown value.
"""
assert is_unknown(val) or val in (0, 1)
self._flags[0].P = val
if not is_unknown(val) and is_number(self.regs['f']):
self.regs['f'] = str((self.getv('f') & 0xFB) | (val << 2))
else:
self.regs['f'] = new_tmp_val()
@property
def S(self):
""" The S flag
"""
return self._flags[0].S
@S.setter
def S(self, val):
""" Sets the S flag, and tries to update the F register accordingly.
If the F register is unknown, sets it with a new unknown value.
"""
assert is_unknown(val) or val in (0, 1)
self._flags[0].S = val
if not is_unknown(val) and is_number(self.regs['f']):
self.regs['f'] = str((self.getv('f') & 0x7F) | (val << 7))
else:
self.regs['f'] = new_tmp_val()
def reset(self, regs=None, mems=None):
""" Initial state
"""
if regs is None:
regs = {}
if mems is None:
mems = {}
self.regs = {}
self.stack = []
self.mem = defaultdict(new_tmp_val16) # Dict of label -> value in memory
self._flags = [Flags(), Flags()]
# # Memory for IX / IY accesses
self.ix_ptr = set()
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()
for i in 'af', 'bc', 'de', 'hl':
self.regs[i] = '{}{}{}'.format(self.regs[i[0]], HL_SEP, self.regs[i[1]])
self.regs["%s'" % i] = '{}{}{}'.format(self.regs["%s'" % i[0]], HL_SEP, self.regs["%s'" % i[1]])
self.regs['ix'] = '{}{}{}'.format(self.regs['ixh'], HL_SEP, self.regs['ixl'])
self.regs['iy'] = '{}{}{}'.format(self.regs['iyh'], HL_SEP, self.regs['iyl'])
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.regs.update(**regs)
self.mem.update(**mems)
for key_ in mems:
idx = idx_args(key_)
if idx:
self.ix_ptr.add(idx)
self.reset_flags()
def reset_flags(self):
""" Resets flags to an "unknown state"
"""
self.C = None
self.Z = None
self.P = None
self.S = None
def clear_idx_reg_refs(self, r):
""" For the given ix/iy, remove all references of it in memory, which are not in the form
ix/iy +/- n
"""
r = r.lower()
assert r in ('ix', 'iy')
for k in list(self.ix_ptr):
if k[0] != r:
continue
if not is_number(k[2]):
del self.mem['{}{}{}'.format(*k)]
self.ix_ptr.remove(k)
def shift_idx_regs_refs(self, r, offset):
""" Given an idx register r (ix / iy) and an offset, all the references in memory
will be shifted the given amount.
I.e. for 'ix', 1
(ix + 1) will contain (ix + 2), and so on.
(ix + 127) will contain an unknown8 value
The same applies for negative offsets. For iy - 2
(iy + 2) will contain current (iy + 0)
(iy - 126) and lower will contain random unknown8
"""
if offset == 0:
return
self.clear_idx_reg_refs(r)
r = r.lower()
if offset > 0:
for i in range(-128, 128):
idx = '%s%+i' % (r, i)
old_idx = '%s%+i' % (r, offset + i)
self.mem[idx] = new_tmp_val() if offset + i > 127 else self.mem[old_idx]
else:
for i in range(127, -129, -1):
idx = '%s%+i' % (r, i)
old_idx = '%s%+i' % (r, offset + i)
self.mem[idx] = new_tmp_val() if offset + i < -128 else self.mem[old_idx]
def set(self, r, val):
val = self.get(val)
is_num = is_number(val)
if val is None:
val = new_tmp_val16()
else:
val = str(val)
if is_num:
val = str(valnum(val) & 0xFFFF)
if self.getv(r) == val:
return # The register already contains this
if r == '(sp)':
if not self.stack:
self.stack = [new_tmp_val16()]
self.stack[-1] = val
return
if r in {'(hl)', '(bc)', '(de)'}: # ld (bc|de|hl), val
r = self.regs[r[1:-1]]
if r in self.mem and val == self.mem[r]:
return # Already set
self.mem[r] = val
return
if r[0] == '(': # (mem) <- r => store in memory address
r = r[1:-1].strip()
idx = idx_args(r)
if idx is not None:
r = "{}{}{}".format(*idx)
self.ix_ptr.add(idx)
val = LO16_val(val)
if r in self.mem and val == self.mem[r]:
return # the same value to the same pos does nothing... (strong assumption: NON-VOLATILE)
self.mem[r] = val
return
if is_8bit_oper_register(r):
oldval = self.getv(r)
if is_num:
val = str(valnum(val) & 0xFF)
else:
val = get_L_from_unknown_value(val)
if val == oldval: # Does not change
return
self.regs[r] = val
if r not in self._16bit:
return
hl = self._16bit[r]
h_ = self.regs[hl[0]]
l_ = self.regs[hl[1]]
if is_number(h_) and is_number(l_):
self.regs[hl] = str((valnum(h_) << 8) | valnum(l_))
return
self.regs[hl] = '{}{}{}'.format(h_, HL_SEP, l_)
return
# a 16 bit reg
assert r in self.regs
assert is_num or is_unknown16(val), "val '{}' is not a number nor an unknown16".format(val)
self.regs[r] = val
if is_16bit_composed_register(r): # sp register is not included. Special case
if not is_num:
self.regs[HI16(r)], self.regs[LO16(r)] = val.split(HL_SEP)
else:
val = valnum(val)
self.regs[HI16(r)], self.regs[LO16(r)] = str(val >> 8), str(val & 0xFF)
if 'f' in r:
self.reset_flags()
def get(self, r):
""" Returns precomputed value of the given expression
"""
if r is None:
return None
r = str(r)
if r.lower() == '(sp)' and self.stack:
return self.stack[-1]
if r.lower() in {'(hl)', '(bc)', '(de)'}:
i = self.regs[r.lower()[1:-1]]
return self.mem[i]
if r[:1] == '(':
v_ = r[1:-1].strip()
idx = idx_args(v_)
if idx is not None:
v_ = "{}{}{}".format(*idx)
self.ix_ptr.add(idx)
val = self.mem[v_]
if idx is not None:
self.mem[v_] = val = LO16_val(val)
return val
if is_number(r):
return str(valnum(r))
if is_unknown(r):
return r
r = r.lower()
if not is_register(r):
return None
return self.regs[r]
def getv(self, r):
""" Like the above, but returns the <int> value or None.
"""
v = self.get(r)
if not is_unknown(v):
try:
v = int(v)
except ValueError:
v = None
else:
v = None
return v
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]
def set_flag(self, val):
if not is_number(val):
self.regs['f'] = new_tmp_val()
self.reset_flags()
return
self.set('f', val)
val = valnum(val)
self.C = val & 1
self.P = (val >> 2) & 1
self.Z = (val >> 6) & 1
self.S = (val >> 7) & 1
def inc(self, r):
""" Does inc on the register and precomputes flags
"""
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
self.C = int(v_ == 0)
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)
if r in ('ix', 'iy'):
self.shift_idx_regs_refs(r, 1)
if not is_8bit_oper_register(r): # INC does not affect flag for 16bit regs
return
if is_unknown(self.regs[r]):
self.set_flag(None)
return
v_ = self.getv(r)
self.Z = int(v_ == 0)
self.C = int(v_ == 0)
def dec(self, r):
""" Does dec on the register and precomputes flags
"""
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
self.C = int(v_ == 0xFF)
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)
if r in ('ix', 'iy'):
self.shift_idx_regs_refs(r, -1)
if not is_8bit_oper_register(r): # DEC does not affect flag for 16bit regs
return
if is_unknown(self.regs[r]):
self.set_flag(None)
return
v_ = self.getv(r)
self.Z = int(v_ == 0)
self.C = int(v_ == 0xFF)
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))
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))
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))
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)
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
def execute(self, asm_code):
""" Tries to update the registers values with the given
asm line.
"""
asm_ = asm.Asm(asm_code)
if asm_.is_label:
return
i = asm_.inst
o = asm_.oper
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']) is not None:
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':
for j in 'bc', 'de', 'hl', 'b', 'c', 'd', 'e', 'h', 'l':
self.regs[j], self.regs["%s'" % j] = self.regs["%s'" % j], self.regs[j]
return
if i == 'ex':
if o == ['de', 'hl']:
for a, b in [('de', 'hl'), ('d', 'h'), ('e', 'l')]:
self.regs[a], self.regs[b] = self.regs[b], self.regs[a]
else:
for j in 'af', 'a', 'f':
self.regs[j], self.regs["%s'" % j] = self.regs["%s'" % j], self.regs[j]
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.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_oper_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_oper_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_oper_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:
self.set('a', None)
return
self.set('a', 0xFF ^ self.getv('a'))
return
if i == 'cp':
val = self.getv(o[0])
if not is_number(self.regs['a']) or is_unknown(val):
self.set_flag(None)
return
val = int(self.regs['a']) - val
self.Z = int(val == 0)
self.C = int(val < 0)
self.S = int(val < 0)
return
if i in {'jp', 'jr', 'ret', 'rst', 'call'}:
return
if i == 'djnz':
if self.getv('b') is None:
self.set('b', None)
self.Z = None
return
val = (self.getv('b') - 1) & 0xFF
self.set('b', val)
self.Z = int(val == 0)
return
if i == 'out':
return
if i == 'in':
self.set(o[0], None)
return
# Unknown. Resets ALL
self.reset()
def __repr__(self):
return '\n'.join('{}: {}'.format(x, y) for x, y in self.regs.items())
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/optimizer/cpustate.py
|
cpustate.py
|
# -*- coding: utf-8 -*-
import re
import itertools
RE_SVAR = re.compile(r'(\$(?:\$|[0-9]+))')
RE_PARSE = re.compile(r'(\s+|"(?:[^"]|"")*")')
class BasicLinePattern(object):
""" Defines a pattern for a line, like 'push $1' being
$1 a pattern variable
"""
@staticmethod
def sanitize(pattern):
""" Returns a sanitized pattern version of a string to be later
compiled into a reg exp
"""
meta = r'.^$*+?{}[]\|()'
return ''.join(r'\%s' % x if x in meta else x for x in pattern)
def __init__(self, line):
self.line = ''.join(x.strip() or ' ' for x in RE_PARSE.split(line) if x).strip()
self.vars = []
self.re_pattern = ''
self.output = []
for token in RE_PARSE.split(self.line):
if token == ' ':
self.re_pattern += r'\s+'
self.output.append(' ')
continue
subtokens = [x for x in RE_SVAR.split(token) if x]
for tok in subtokens:
if tok == '$$':
self.re_pattern += r'\$'
self.output.append('$')
elif RE_SVAR.match(tok):
self.output.append(tok)
mvar = '_%s' % tok[1:]
if mvar not in self.vars:
self.vars.append(mvar)
self.re_pattern += '(?P<%s>.*)' % mvar
else:
self.re_pattern += r'\%i' % (self.vars.index(mvar) + 1)
else:
self.output.append(tok)
self.re_pattern += BasicLinePattern.sanitize(tok)
self.re = re.compile(self.re_pattern)
self.vars = set(x.replace('_', '$') for x in self.vars)
class LinePattern(BasicLinePattern):
""" Defines a pattern to match against a source assembler.
Given an assembler instruction with substitution variables
($1, $2, ...) creates an instance that matches against a list real
assembler instructions. e.g.
push $1
matches against
push af
and bounds $1 to 'af'
Note that $$ matches against the $ sign
"""
def match(self, line, vars_=None):
match = self.re.match(line)
if match is None:
return None
vars__ = {'_%s' % k[1:]: v for k, v in (vars_ or {}).items()}
for k, v in vars__.items():
if match.groupdict().get(k, v) != v:
return None
result = dict(vars_ or {})
result.update({'$%s' % k[1:]: v for k, v in match.groupdict().items()})
return result
def __repr__(self):
return repr(self.re)
class BlockPattern(object):
""" Given a list asm instructions, tries to match them
"""
def __init__(self, lines):
lines = [x.strip() for x in lines]
self.patterns = [LinePattern(x) for x in lines if x]
self.lines = [pattern.line for pattern in self.patterns]
self.vars = set(itertools.chain(*[p.vars for p in self.patterns]))
def __len__(self):
return len(self.lines)
def match(self, instructions, start=0):
""" Given a list of instructions and a starting point,
returns whether this pattern matches or not from such point
onwards.
E.g. given the pattern:
push $1
pop $1
and the list
ld a, 5
push af
pop af
this pattern will match at position 1
"""
lines = instructions[start:]
if len(self) > len(lines):
return None
univars = {}
for patt, line in zip(self.patterns, lines):
univars = patt.match(line, vars_=univars)
if univars is None:
return None
return univars
def __repr__(self):
return str([repr(x) for x in self.patterns])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/peephole/pattern.py
|
pattern.py
|
# -*- coding: utf-8 -*-
import re
from api import utils
from .template import UnboundVarError
from .pattern import RE_SVAR
from ..optimizer import helpers
from ..optimizer import memcell
OP_NOT = '!'
OP_PLUS = '+'
OP_EQ = '=='
OP_NE = '<>'
OP_AND = '&&'
OP_OR = '||'
OP_IN = 'IN'
OP_COMMA = ','
OP_NPLUS = '.+'
OP_NSUB = '.-'
OP_NMUL = '.*'
OP_NDIV = './'
# Reg expr patterns
RE_IXIY_IDX = re.compile(r'^\([ \t]*i[xy][ \t]*[-+][ \t]*.+\)$')
# Unary functions and operators
UNARY = {
OP_NOT: lambda x: not x,
'IS_ASM': lambda x: x.startswith('##ASM'),
'IS_INDIR': lambda x: RE_IXIY_IDX.match(x),
'IS_REG16': lambda x: x.strip().lower() in ('af', 'bc', 'de', 'hl', 'ix', 'iy'),
'IS_REG8': lambda x: x.strip().lower() in ('a', 'b', 'c', 'd', 'e', 'h', 'l', 'ixh', 'ixl', 'iyh', 'iyl'),
'IS_LABEL': lambda x: x.strip()[-1:] == ':',
'LEN': lambda x: str(len(x.split())),
'INSTR': lambda x: x.strip().split()[0],
'HIREG': lambda x: {
'af': 'a',
'bc': 'b',
'de': 'd',
'hl': 'h',
'ix': 'ixh',
'iy': 'iyh'}.get(x.strip().lower(), ''),
'LOREG': lambda x: {
'af': 'f',
'bc': 'c',
'de': 'e',
'hl': 'l',
'ix': 'ixl',
'iy': 'iyl'}.get(x.strip().lower(), ''),
'HIVAL': helpers.HI16_val,
'LOVAL': helpers.LO16_val,
'GVAL': lambda x: helpers.new_tmp_val(), # To be updated in the O3 optimizer
'IS_REQUIRED': lambda x: True, # by default always required
'CTEST': lambda x: memcell.MemCell(x, 1).condition_flag, # condition test, if any. E.g. retz returns 'z'
'NEEDS': lambda x: memcell.MemCell(x[0], 1).needs(x[1]),
'FLAGVAL': lambda x: helpers.new_tmp_val()
}
# Binary operators
BINARY = {
OP_EQ: lambda x, y: x() == y(),
OP_PLUS: lambda x, y: x() + y(),
OP_NE: lambda x, y: x() != y(),
OP_AND: lambda x, y: x() and y(),
OP_OR: lambda x, y: x() or y(),
OP_IN: lambda x, y: x() in y(),
OP_COMMA: lambda x, y: [x(), y()],
OP_NPLUS: lambda x, y: str(Number(x()) + Number(y())),
OP_NSUB: lambda x, y: str(Number(x()) - Number(y())),
OP_NMUL: lambda x, y: str(Number(x()) * Number(y())),
OP_NDIV: lambda x, y: str(Number(x()) / Number(y()))
}
OPERS = set(BINARY.keys()).union(UNARY.keys())
class Number(object):
""" Emulates a number that can be also None
"""
def __init__(self, value):
if isinstance(value, Number):
value = value.value
self.value = utils.parse_int(str(value))
def __repr__(self):
return str(self.value) if self.value is not None else ''
def __str__(self):
return repr(self)
def __add__(self, other):
assert isinstance(other, Number)
if self.value is None or other.value is None:
return Number('')
return Number(self.value + other.value)
def __sub__(self, other):
assert isinstance(other, Number)
if self.value is None or other.value is None:
return Number('')
return Number(self.value - other.value)
def __mul__(self, other):
assert isinstance(other, Number)
if self.value is None or other.value is None:
return Number('')
return Number(self.value * other.value)
def __floordiv__(self, other):
assert isinstance(other, Number)
if self.value is None or other.value is None:
return Number('')
if not other.value:
return None # Div by Zero
return Number(self.value / other.value)
def __truediv__(self, other):
return self.__floordiv__(other)
class Evaluator(object):
""" Evaluates a given expression, which comes as an AST in nested lists. For example:
["ab" == ['a' + 'b']] will be evaluated as true.
[5] will return 5
[!0] will return True
Operators:
Unary:
! (not)
Binary:
== (equality)
!= (non equality)
&& (and)
|| (or)
+ (addition or concatenation for strings)
"""
UNARY = UNARY
BINARY = BINARY
def __init__(self, expression, unary=None, binary=None):
""" Initializes the object parsing the expression and preparing it for its (later)
execution.
:param expression: An expression (an AST in nested list parsed from the parser module
:param unary: optional dict of unary functions (defaults to UNARY)
:param binary: optional dict of binary operators (defaults to BINARY)
"""
self.str_ = str(expression)
self.unary = unary if unary is not None else Evaluator.UNARY
self.binary = binary if binary is not None else Evaluator.BINARY
if not isinstance(expression, list):
expression = [expression]
if not expression:
self.expression = [True]
elif len(expression) == 1:
self.expression = expression
elif len(expression) == 2:
if expression[0] not in self.unary:
raise ValueError("Invalid operator '{0}'".format(expression[0]))
self.expression = expression
expression[1] = Evaluator(expression[1])
elif len(expression) == 3 and expression[1] != OP_COMMA:
if expression[1] not in self.binary:
raise ValueError("Invalid operator '{0}'".format(expression[1]))
self.expression = expression
expression[0] = Evaluator(expression[0])
expression[2] = Evaluator(expression[2])
else: # It's a list
assert len(expression) % 2 # Must be odd length
assert all(x == OP_COMMA for i, x in enumerate(expression) if i % 2)
self.expression = [Evaluator(x) if not i % 2 else x for i, x in enumerate(expression)]
def normalize(self, value):
""" If a value is of type boolean converts it to string,
returning "" for False, or the value to string for true.
"""
if not value:
return ""
return str(value)
def eval(self, vars_=None):
if vars_ is None:
vars_ = {}
if len(self.expression) == 1:
val = self.expression[0]
if not isinstance(val, str):
return val
if val == '$':
return val
if not RE_SVAR.match(val):
return val
if val not in vars_:
raise UnboundVarError("Unbound variable '{0}'".format(val))
return vars_[val]
if len(self.expression) == 2:
oper = self.expression[0]
assert oper in self.unary
operand = self.expression[1].eval(vars_)
return self.normalize(self.unary[oper](operand))
if len(self.expression) == 3 and self.expression[1] != OP_COMMA:
assert self.expression[1] in self.binary
# Do lazy evaluation
left_ = lambda: self.expression[0].eval(vars_)
right_ = lambda: self.expression[2].eval(vars_)
return self.normalize(self.binary[self.expression[1]](left_, right_))
# It's a list
return [x.eval(vars_) for i, x in enumerate(self.expression) if not i % 2]
def __eq__(self, other):
return self.expression == other.expression
def __repr__(self):
return self.str_
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/peephole/evaluator.py
|
evaluator.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
from collections import defaultdict, namedtuple
import api
from arch.zx48k.peephole import evaluator
from arch.zx48k.peephole import parser
from arch.zx48k.peephole import pattern
from arch.zx48k.peephole import template
from arch.zx48k.peephole.parser import REG_IF, REG_REPLACE, REG_DEFINE, REG_WITH, O_LEVEL, O_FLAG
OptPattern = namedtuple('OptPattern',
('level', 'flag', 'patt', 'cond', 'template', 'parsed', 'defines', 'fname'))
OPTS_PATH = os.path.join(os.path.dirname(__file__), 'opts')
# Global list of optimization patterns
PATTERNS = []
# Max len of any pattern read
MAXLEN = None
def read_opt(opt_path):
""" Given a path to an opt file, parses it and returns an OptPattern
object, or None if there were errors
"""
global MAXLEN
fpath = os.path.abspath(opt_path)
if not os.path.isfile(fpath):
return
parsed_result = parser.parse_file(fpath)
if parsed_result is None:
return
try:
pattern_ = OptPattern(
level=parsed_result[O_LEVEL],
flag=parsed_result[O_FLAG],
patt=pattern.BlockPattern(parsed_result[REG_REPLACE]),
template=template.BlockTemplate(parsed_result[REG_WITH]),
cond=evaluator.Evaluator(parsed_result[REG_IF]),
parsed=parsed_result,
defines=parsed_result[REG_DEFINE],
fname=os.path.basename(fpath))
for var_, define_ in pattern_.defines:
if var_ in pattern_.patt.vars:
api.errmsg.warning(define_.lineno, "variable '{0}' already defined in pattern".format(var_), fpath)
api.errmsg.warning(define_.lineno, "this template will be ignored", fpath)
return
except (ValueError, KeyError, TypeError):
api.errmsg.warning(1, "There is an error in this template and it will be ignored", fpath)
else:
MAXLEN = max(len(pattern_.patt), MAXLEN or 0)
return pattern_
def read_opts(folder_path, result=None):
""" Reads (and parses) all *.opt files from the given directory
retaining only those with no errors.
"""
if result is None:
result = defaultdict(list)
try:
files_to_read = [f for f in os.listdir(folder_path) if f.endswith('.opt')]
except (FileNotFoundError, NotADirectoryError, PermissionError):
return result
for fname in files_to_read:
pattern_ = read_opt(os.path.join(folder_path, fname))
if pattern_ is None:
continue
result.append(pattern_)
result[:] = sorted(result, key=lambda x: x.flag)
return result
def apply_match(asm_list, patterns_list, index=0):
""" Tries to match optimization patterns against the given ASM list block, starting
at offset `index` within that block.
Only patterns having an O_LEVEL between o_min and o_max (both included) will be taken
into account.
:param asm_list: A list of asm instructions (will be changed)
:param patterns_list: A list of OptPatterns to try against
:param index: Index to start matching from (defaults to 0)
:param o_min: Minimum O level to use (defaults to 0)
:param o_max: Maximum O level to use (defaults to inf)
:return: True if there was a match and asm_list code was changed
"""
for p in patterns_list:
match = p.patt.match(asm_list, start=index)
if match is None: # HINT: {} is also a valid match
continue
for var, defline in p.defines:
match[var] = defline.expr.eval(match)
if not p.cond.eval(match):
continue
# All patterns have matched successfully. Apply this pattern
matched = asm_list[index: index + len(p.patt)]
applied = p.template.filter(match)
asm_list[index: index + len(p.patt)] = applied
api.errmsg.info('pattern applied [{}:{}]'.format("%03i" % p.flag, p.fname))
api.debug.__DEBUG__('matched: \n {}'.format('\n '.join(matched)), level=1)
return True
return False
def init():
global PATTERNS
global MAXLEN
PATTERNS = []
MAXLEN = 0
def main(list_of_directories=None):
""" Initializes the module and load all the *.opt files
containing patterns and parses them. Valid .opt files will be stored in
PATTERNS
"""
global PATTERNS
global MAXLEN
if MAXLEN:
return
init()
if not list_of_directories:
list_of_directories = [OPTS_PATH]
for directory in list_of_directories:
read_opts(directory, PATTERNS)
if __name__ == '__main__':
main(sys.argv[1:])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/peephole/engine.py
|
engine.py
|
# -*- coding: utf-8 -*-
from .pattern import BasicLinePattern
class UnboundVarError(ValueError):
pass
class LineTemplate(BasicLinePattern):
""" Given a template line (i.e. 'push $1') and a dictionary
of variables {'$1': value1, '$2': value2} replaces such variables
with their values. '$$' is replaced by '$'. If any variable is unbound,
an assertion is raised.
"""
def filter(self, vars_=None):
""" Applies a list of vars to the given pattern and returns the line
"""
vars_ = vars_ or {}
result = ''
for tok in self.output:
if len(tok) > 1 and tok[0] == '$':
val = vars_.get(tok, None)
if val is None:
raise UnboundVarError("Unbound variable {0}".format(tok))
result += val
else:
result += tok
return result.strip()
def __repr__(self):
return self.line
class BlockTemplate(object):
""" Extends a Line template to a block of them
"""
def __init__(self, lines):
lines = [x.strip() for x in lines]
self.templates = [LineTemplate(x) for x in lines if x]
def filter(self, vars_=None):
return [y for y in [x.filter(vars_) for x in self.templates] if y]
def __repr__(self):
return repr([repr(x) for x in self.templates])
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/peephole/template.py
|
template.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
from collections import defaultdict, namedtuple
import api.errmsg
import api.global_
from . import evaluator
from . import pattern
COMMENT = ';;'
RE_REGION = re.compile(r'([_a-zA-Z][a-zA-Z0-9]*)[ \t]*{{')
RE_DEF = re.compile(r'([_a-zA-Z][a-zA-Z0-9]*)[ \t]*:[ \t]*(.*)')
RE_IFPARSE = re.compile(r'"(""|[^"])*"|[(),]|\b[_a-zA-Z]+\b|[^," \t()]+')
RE_ID = re.compile(r'\b[_a-zA-Z]+\b')
# Names of the different params
REG_IF = 'IF'
REG_REPLACE = 'REPLACE'
REG_WITH = 'WITH'
REG_DEFINE = 'DEFINE'
O_LEVEL = 'OLEVEL'
O_FLAG = 'OFLAG'
# Operators : priority (lower number -> highest priority)
IF_OPERATORS = {
evaluator.OP_NMUL: 3,
evaluator.OP_NDIV: 3,
evaluator.OP_PLUS: 5,
evaluator.OP_NPLUS: 5,
evaluator.OP_NSUB: 5,
evaluator.OP_NE: 10,
evaluator.OP_EQ: 10,
evaluator.OP_AND: 15,
evaluator.OP_OR: 20,
evaluator.OP_IN: 25,
evaluator.OP_COMMA: 30
}
# Which one of the above are REGIONS (that is, {{ ... }} blocks)
REGIONS = {REG_IF, REG_WITH, REG_REPLACE, REG_DEFINE}
# Which one of the above are scalars (NAME: VALUE definitions)
SCALARS = {O_FLAG, O_LEVEL}
# Which one of the above must be integers (0...N)
NUMERIC = {O_FLAG, O_LEVEL}
# Put here all of the above that are required
REQUIRED = (REG_REPLACE, REG_WITH, O_LEVEL, O_FLAG)
def flatten(expr):
if not isinstance(expr, list):
return expr
if len(expr) == 1 and isinstance(expr[0], list):
return flatten(expr[0])
return [flatten(x) for x in expr]
# Stores a source opt line
SourceLine = namedtuple('SourceLine', ('lineno', 'line'))
# Defines a define expr with its linenum
DefineLine = namedtuple('DefineLine', ('lineno', 'expr'))
def parse_ifline(if_line, lineno):
""" Given a line from within a IF region (i.e. $1 == "af'")
returns it as a list of tokens ['$1', '==', "af'"]
"""
stack = []
expr = []
paren = 0
error_ = False
while not error_ and if_line:
if_line = if_line.strip()
if not if_line:
break
qq = RE_IFPARSE.match(if_line)
if not qq:
error_ = True
break
tok = qq.group()
if not RE_ID.match(tok):
for op in evaluator.OPERS:
if tok.startswith(op):
tok = tok[:len(op)]
break
if_line = if_line[len(tok):]
if tok == '(':
paren += 1
stack.append(expr)
expr = []
continue
if tok in evaluator.UNARY:
stack.append(expr)
expr = [tok]
continue
if tok == ')':
paren -= 1
if paren < 0:
api.errmsg.warning(lineno, "Too much closed parenthesis")
return
if expr and expr[-1] == evaluator.OP_COMMA:
api.errmsg.warning(lineno, "missing element in list")
return
stack[-1].append(expr)
expr = stack.pop()
else:
if len(tok) > 1 and tok[0] == tok[-1] == '"':
tok = tok[1:-1]
expr.append(tok)
if tok == evaluator.OP_COMMA:
if len(expr) < 2 or expr[-2] == tok:
api.errmsg.warning(lineno, "Unexpected {} in list".format(tok))
return
while len(expr) == 2 and isinstance(expr[-2], str):
op = expr[-2]
if op in evaluator.UNARY:
stack[-1].append(expr)
expr = stack.pop()
else:
break
if len(expr) == 3 and expr[1] != evaluator.OP_COMMA:
left_, op, right_ = expr
if not isinstance(op, str) or op not in IF_OPERATORS:
api.errmsg.warning(lineno, "Unexpected binary operator '{0}'".format(op))
return
if isinstance(left_, list) and len(left_) == 3 and IF_OPERATORS[left_[-2]] > IF_OPERATORS[op]:
expr = [[left_[:-2], left_[-2], [left_[-1], op, right_]]] # Rebalance tree
else:
expr = [expr]
if not error_ and paren:
api.errmsg.warning(lineno, "unclosed parenthesis in IF section")
return
while stack and not error_:
stack[-1].append(expr)
expr = stack.pop()
if len(expr) == 2:
op = expr[0]
if not isinstance(op, str) or op not in evaluator.UNARY:
api.errmsg.warning(lineno, "unexpected unary operator '{0}'".format(op))
return
elif len(expr) == 3:
op = expr[1]
if not isinstance(op, str) or op not in evaluator.BINARY:
api.errmsg.warning(lineno, "unexpected binary operator '{0}'".format(op))
return
if error_:
api.errmsg.warning(lineno, "syntax error in IF section")
return
return flatten(expr)
def parse_define_line(sourceline):
""" Given a line $nnn = <expression>, returns a tuple the parsed
("$var", [expression]) or None, None if error. """
if '=' not in sourceline.line:
api.errmsg.warning(sourceline.lineno, "assignation '=' not found")
return None, None
result = [x.strip() for x in sourceline.line.split('=', 1)]
if not pattern.RE_SVAR.match(result[0]): # Define vars
api.errmsg.warning(sourceline.lineno, "'{0}' not a variable name".format(result[0]))
return None, None
result[1] = parse_ifline(result[1], sourceline.lineno)
if result[1] is None:
return None, None
return result
def parse_str(spec):
""" Given a string with an optimizer template definition,
parses it and return a python object as a result.
If any error is detected, fname will be used as filename.
"""
# States
ST_INITIAL = 0
ST_REGION = 1
result = defaultdict(list)
state = ST_INITIAL
line_num = 0
region_name = None
is_ok = True
re_int = re.compile(r'^\d+$')
def add_entry(key, val):
key = key.upper()
if key in result:
api.errmsg.warning(line_num, "duplicated definition {0}".format(key))
return False
if key not in REGIONS and key not in SCALARS:
api.errmsg.warning(line_num, "unknown definition parameter '{0}'".format(key))
return False
if key in NUMERIC:
if not re_int.match(val):
api.errmsg.warning(line_num, "field '{0} must be integer".format(key))
return False
val = int(val)
result[key] = val
return True
def check_entry(key):
if key not in result:
api.errmsg.warning(line_num, "undefined section {0}".format(key))
return False
return True
for line in spec.split('\n'):
line = line.strip()
line_num += 1
if not line:
continue # Ignore blank lines
if state == ST_INITIAL:
if line.startswith(COMMENT):
continue
x = RE_REGION.match(line)
if x:
region_name = x.groups()[0]
state = ST_REGION
add_entry(region_name, [])
continue
x = RE_DEF.match(line)
if x:
if not add_entry(*x.groups()):
is_ok = False
break
continue
elif state == ST_REGION:
if line.endswith('}}'):
line = line[:-2].strip()
state = ST_INITIAL
if line:
result[region_name].append(SourceLine(line_num, line))
if state == ST_INITIAL:
region_name = None
continue
api.errmsg.warning(line_num, "syntax error. Cannot parse file")
is_ok = False
break
defines = []
defined_vars = set()
for source_line in result[REG_DEFINE]:
var_, expr = parse_define_line(source_line)
if var_ is None or expr is None:
is_ok = False
break
if var_ in defined_vars:
api.errmsg.warning(source_line.lineno, "duplicated variable '{0}'".format(var_))
is_ok = False
break
defines.append([var_, DefineLine(expr=evaluator.Evaluator(expr), lineno=source_line.lineno)])
defined_vars.add(var_)
result[REG_DEFINE] = defines
if is_ok:
for reg in [x for x in REGIONS if x != REG_DEFINE]:
result[reg] = [x.line for x in result[reg]]
if is_ok:
result[REG_IF] = parse_ifline(' '.join(x for x in result[REG_IF]), line_num)
if result[REG_IF] is None:
is_ok = False
is_ok = is_ok and all(check_entry(x) for x in REQUIRED)
if is_ok:
if not result[REG_REPLACE]: # Empty REPLACE region??
api.errmsg.warning(line_num, "empty region {0}".format(REG_REPLACE))
is_ok = False
if not is_ok:
api.errmsg.warning(line_num, "this optimizer template will be ignored due to errors")
return
return result
def parse_file(fname):
""" Opens and parse a file given by filename
"""
tmp = api.global_.FILENAME
api.global_.FILENAME = fname # set filename so it shows up in error/warning msgs
with open(fname, 'rt') as f:
result = parse_str(f.read())
api.global_.FILENAME = tmp # restores original filename
return result
if __name__ == '__main__':
print(parse_file(sys.argv[1]))
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/peephole/parser.py
|
parser.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
# --------------------------------------------------------------
# Copyleft (k) 2008, by Jose M. Rodriguez-Rosa
# (a.k.a. Boriel, http://www.boriel.com)
#
# This module contains string arithmetic and
# comparation intermediate-code traductions
# --------------------------------------------------------------
from .__common import REQUIRES
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] == '#': # Immediate
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 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)
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
def _addstr(ins):
''' Adds 2 string values. The result is pushed onto the stack.
Note: This instruction does admit direct strings (as labels).
'''
(tmp1, tmp2, output) = _str_oper(ins.quad[2], ins.quad[3], no_exaf=True)
if tmp1:
output.append('push hl')
if tmp2:
output.append('push de')
output.append('call __ADDSTR')
output.extend(_free_sequence(tmp1, tmp2))
output.append('push hl')
REQUIRES.add('strcat.asm')
return output
def _ltstr(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 __STRLT')
output.append('push af')
REQUIRES.add('string.asm')
return output
def _gtstr(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 __STRGT')
output.append('push af')
REQUIRES.add('string.asm')
return output
def _lestr(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 __STRLE')
output.append('push af')
REQUIRES.add('string.asm')
return output
def _gestr(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 __STRGE')
output.append('push af')
REQUIRES.add('string.asm')
return output
def _eqstr(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 __STREQ')
output.append('push af')
REQUIRES.add('string.asm')
return output
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
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
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/backend/__str.py
|
__str.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim:ts=4:et:sw=4:
# --------------------------------------------------------------
# Copyleft (k) 2008, by Jose M. Rodriguez-Rosa
# (a.k.a. Boriel, http://www.boriel.com)
#
# This module contains local array (both parameters and
# comparation intermediate-code traductions
# --------------------------------------------------------------
from api import fp
from .__common import REQUIRES
from .__float import _fpush
from .__f16 import f16
def _paddr(offset):
""" Generic element array-address stack-ptr loading.
Emits output code for setting IX at the right location.
bytes = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
"""
output = []
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
output.append('call __ARRAY_PTR')
else:
output.append('call __ARRAY')
REQUIRES.add('array.asm')
return output
def _paaddr(ins):
""" Loads address of an array element into the stack
"""
output = _paddr(ins.quad[2])
output.append('push hl')
return output
def _paload8(ins):
""" Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _paddr(ins.quad[2])
output.append('ld a, (hl)')
output.append('push af')
return output
def _paload16(ins):
""" Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _paddr(ins.quad[2])
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld d, (hl)')
output.append('ex de, hl')
output.append('push hl')
return output
def _paload32(ins):
""" Loads a 32 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _paddr(ins.quad[2])
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
REQUIRES.add('iload32.asm')
return output
def _paloadf(ins):
""" Loads a floating point value from a memory address.
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _paddr(ins.quad[2])
output.append('call __ILOADF')
output.extend(_fpush())
REQUIRES.add('iloadf.asm')
return output
def _paloadstr(ins):
""" Loads a string value from a memory address.
"""
output = _paddr(ins.quad[2])
output.append('call __ILOADSTR')
output.append('push hl')
REQUIRES.add('loadstr.asm')
return output
def _pastore8(ins):
""" Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array)
"""
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFF
if indirect:
output.append('ld a, (%i)' % value)
output.append('ld (hl), a')
else:
value &= 0xFF
output.append('ld (hl), %i' % value)
except ValueError:
output.append('pop af')
output.append('ld (hl), a')
return output
def _pastore16(ins):
""" Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
"""
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFF
output.append('ld de, %i' % value)
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
except ValueError:
output.append('pop de')
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
return output
def _pastore32(ins):
""" Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
"""
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFFFFFF # Immediate?
if indirect:
output.append('push hl')
output.append('ld hl, %i' % (value & 0xFFFF))
output.append('call __ILOAD32')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits
output.append('pop hl')
REQUIRES.add('iload32.asm')
else:
output.append('ld de, %i' % (value >> 16))
output.append('ld bc, %i' % (value & 0xFFFF))
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('call __STORE32')
REQUIRES.add('store32.asm')
return output
def _pastoref16(ins):
""" Stores 2º operand content into address of 1st operand.
storef16 a, x => *(&a) = x
"""
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
if indirect:
value = int(ins.quad[2])
output.append('push hl')
output.append('ld hl, %i' % (value & 0xFFFF))
output.append('call __ILOAD32')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits
output.append('pop hl')
REQUIRES.add('iload32.asm')
else:
de, hl = f16(value)
output.append('ld de, %i' % de)
output.append('ld bc, %i' % hl)
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('call __STORE32')
REQUIRES.add('store32.asm')
return output
def _pastoref(ins):
""" Stores a floating point value into a memory address.
"""
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
if indirect:
value = int(value) & 0xFFFF # Immediate?
output.append('push hl')
output.append('ld hl, %i' % value)
output.append('call __ILOADF')
output.append('ld a, c')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits, A = Exp
output.append('pop hl') # Recovers pointer
REQUIRES.add('iloadf.asm')
else:
value = float(value) # Immediate?
C, DE, HL = fp.immediate_float(value)
output.append('ld a, %s' % C)
output.append('ld de, %s' % DE)
output.append('ld bc, %s' % HL)
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('ex (sp), hl') # Preserve HL for STOREF
output.append('ld a, l')
output.append('pop hl')
output.append('call __STOREF')
REQUIRES.add('storef.asm')
return output
def _pastorestr(ins):
""" Stores a string value into a memory address.
It copies content of 2nd operand (string), into 1st, reallocating
dynamic memory for the 1st str. These instruction DOES ALLOW
immediate strings for the 2nd parameter, starting with '#'.
"""
output = _paddr(ins.quad[1])
temporal = False
value = ins.quad[2]
indirect = value[0] == '*'
if indirect:
value = value[1:]
immediate = value[0]
if immediate:
value = value[1:]
if value[0] == '_':
if indirect:
if immediate:
output.append('ld de, (%s)' % value)
else:
output.append('ld de, (%s)' % value)
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
else:
if immediate:
output.append('ld de, %s' % value)
else:
output.append('ld de, (%s)' % value)
else:
output.append('pop de')
temporal = True
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
if not temporal:
output.append('call __STORE_STR')
REQUIRES.add('storestr.asm')
else: # A value already on dynamic memory
output.append('call __STORE_STR2')
REQUIRES.add('storestr2.asm')
return output
|
zxbasic
|
/zxbasic-1.12.0.tar.gz/zxbasic-1.12.0/arch/zx48k/backend/__parray.py
|
__parray.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.