repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
boriel/zxbasic
prepro/definestable.py
DefinesTable.set
def set(self, id_, lineno, value='', fname=None, args=None): """ Like the above, but issues no warning on duplicate macro definitions. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] self.table[id_] = ID(id_, args, value, lineno, fname)
python
def set(self, id_, lineno, value='', fname=None, args=None): """ Like the above, but issues no warning on duplicate macro definitions. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] self.table[id_] = ID(id_, args, value, lineno, fname)
[ "def", "set", "(", "self", ",", "id_", ",", "lineno", ",", "value", "=", "''", ",", "fname", "=", "None", ",", "args", "=", "None", ")", ":", "if", "fname", "is", "None", ":", "if", "CURRENT_FILE", ":", "fname", "=", "CURRENT_FILE", "[", "-", "1", "]", "else", ":", "# If no files opened yet, use owns program fname", "fname", "=", "sys", ".", "argv", "[", "0", "]", "self", ".", "table", "[", "id_", "]", "=", "ID", "(", "id_", ",", "args", ",", "value", ",", "lineno", ",", "fname", ")" ]
Like the above, but issues no warning on duplicate macro definitions.
[ "Like", "the", "above", "but", "issues", "no", "warning", "on", "duplicate", "macro", "definitions", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/definestable.py#L47-L56
boriel/zxbasic
arch/zx48k/backend/__common.py
_int_ops
def _int_ops(op1, op2, swap=True): """ Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type. """ if is_int(op1): if swap: return op2, int(op1) else: return int(op1), op2 if is_int(op2): return op1, int(op2) return None
python
def _int_ops(op1, op2, swap=True): """ Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type. """ if is_int(op1): if swap: return op2, int(op1) else: return int(op1), op2 if is_int(op2): return op1, int(op2) return None
[ "def", "_int_ops", "(", "op1", ",", "op2", ",", "swap", "=", "True", ")", ":", "if", "is_int", "(", "op1", ")", ":", "if", "swap", ":", "return", "op2", ",", "int", "(", "op1", ")", "else", ":", "return", "int", "(", "op1", ")", ",", "op2", "if", "is_int", "(", "op2", ")", ":", "return", "op1", ",", "int", "(", "op2", ")", "return", "None" ]
Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type.
[ "Receives", "a", "list", "with", "two", "strings", "(", "operands", ")", ".", "If", "none", "of", "them", "contains", "integers", "returns", "None", ".", "Otherwise", "returns", "a", "t", "-", "uple", "with", "(", "op", "[", "0", "]", "op", "[", "1", "]", ")", "where", "op", "[", "1", "]", "is", "the", "integer", "one", "(", "the", "list", "is", "swapped", ")", "unless", "swap", "is", "False", "(", "e", ".", "g", ".", "sub", "and", "div", "used", "this", "because", "they", "re", "not", "commutative", ")", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__common.py#L124-L143
boriel/zxbasic
arch/zx48k/backend/__common.py
_f_ops
def _f_ops(op1, op2, swap=True): """ Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type. """ if is_float(op1): if swap: return op2, float(op1) else: return float(op1), op2 if is_float(op2): return op1, float(op2) return None
python
def _f_ops(op1, op2, swap=True): """ Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type. """ if is_float(op1): if swap: return op2, float(op1) else: return float(op1), op2 if is_float(op2): return op1, float(op2) return None
[ "def", "_f_ops", "(", "op1", ",", "op2", ",", "swap", "=", "True", ")", ":", "if", "is_float", "(", "op1", ")", ":", "if", "swap", ":", "return", "op2", ",", "float", "(", "op1", ")", "else", ":", "return", "float", "(", "op1", ")", ",", "op2", "if", "is_float", "(", "op2", ")", ":", "return", "op1", ",", "float", "(", "op2", ")", "return", "None" ]
Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they're not commutative). The integer operand is always converted to int type.
[ "Receives", "a", "list", "with", "two", "strings", "(", "operands", ")", ".", "If", "none", "of", "them", "contains", "integers", "returns", "None", ".", "Otherwise", "returns", "a", "t", "-", "uple", "with", "(", "op", "[", "0", "]", "op", "[", "1", "]", ")", "where", "op", "[", "1", "]", "is", "the", "integer", "one", "(", "the", "list", "is", "swapped", ")", "unless", "swap", "is", "False", "(", "e", ".", "g", ".", "sub", "and", "div", "used", "this", "because", "they", "re", "not", "commutative", ")", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__common.py#L146-L165
boriel/zxbasic
symbols/call.py
SymbolCALL.make_node
def make_node(cls, id_, params, lineno): """ This will return an AST node for a function/procedure call. """ assert isinstance(params, SymbolARGLIST) entry = gl.SYMBOL_TABLE.access_func(id_, lineno) if entry is None: # A syntax / semantic error return None if entry.callable is False: # Is it NOT callable? if entry.type_ != Type.string: errmsg.syntax_error_not_array_nor_func(lineno, id_) return None gl.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno) entry.accessed = True if entry.declared and not entry.forwarded: check_call_arguments(lineno, id_, params) else: # All functions goes to global scope by default if not isinstance(entry, SymbolFUNCTION): entry = SymbolVAR.to_function(entry, lineno) gl.SYMBOL_TABLE.move_to_global_scope(id_) gl.FUNCTION_CALLS.append((id_, params, lineno,)) return cls(entry, params, lineno)
python
def make_node(cls, id_, params, lineno): """ This will return an AST node for a function/procedure call. """ assert isinstance(params, SymbolARGLIST) entry = gl.SYMBOL_TABLE.access_func(id_, lineno) if entry is None: # A syntax / semantic error return None if entry.callable is False: # Is it NOT callable? if entry.type_ != Type.string: errmsg.syntax_error_not_array_nor_func(lineno, id_) return None gl.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno) entry.accessed = True if entry.declared and not entry.forwarded: check_call_arguments(lineno, id_, params) else: # All functions goes to global scope by default if not isinstance(entry, SymbolFUNCTION): entry = SymbolVAR.to_function(entry, lineno) gl.SYMBOL_TABLE.move_to_global_scope(id_) gl.FUNCTION_CALLS.append((id_, params, lineno,)) return cls(entry, params, lineno)
[ "def", "make_node", "(", "cls", ",", "id_", ",", "params", ",", "lineno", ")", ":", "assert", "isinstance", "(", "params", ",", "SymbolARGLIST", ")", "entry", "=", "gl", ".", "SYMBOL_TABLE", ".", "access_func", "(", "id_", ",", "lineno", ")", "if", "entry", "is", "None", ":", "# A syntax / semantic error", "return", "None", "if", "entry", ".", "callable", "is", "False", ":", "# Is it NOT callable?", "if", "entry", ".", "type_", "!=", "Type", ".", "string", ":", "errmsg", ".", "syntax_error_not_array_nor_func", "(", "lineno", ",", "id_", ")", "return", "None", "gl", ".", "SYMBOL_TABLE", ".", "check_class", "(", "id_", ",", "CLASS", ".", "function", ",", "lineno", ")", "entry", ".", "accessed", "=", "True", "if", "entry", ".", "declared", "and", "not", "entry", ".", "forwarded", ":", "check_call_arguments", "(", "lineno", ",", "id_", ",", "params", ")", "else", ":", "# All functions goes to global scope by default", "if", "not", "isinstance", "(", "entry", ",", "SymbolFUNCTION", ")", ":", "entry", "=", "SymbolVAR", ".", "to_function", "(", "entry", ",", "lineno", ")", "gl", ".", "SYMBOL_TABLE", ".", "move_to_global_scope", "(", "id_", ")", "gl", ".", "FUNCTION_CALLS", ".", "append", "(", "(", "id_", ",", "params", ",", "lineno", ",", ")", ")", "return", "cls", "(", "entry", ",", "params", ",", "lineno", ")" ]
This will return an AST node for a function/procedure call.
[ "This", "will", "return", "an", "AST", "node", "for", "a", "function", "/", "procedure", "call", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/call.py#L75-L99
boriel/zxbasic
symbols/paramlist.py
SymbolPARAMLIST.make_node
def make_node(clss, 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 insances ''' if node is None: node = clss() if node.token != 'PARAMLIST': return clss.make_node(None, node, *params) for i in params: if i is not None: node.appendChild(i) return node
python
def make_node(clss, 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 insances ''' if node is None: node = clss() if node.token != 'PARAMLIST': return clss.make_node(None, node, *params) for i in params: if i is not None: node.appendChild(i) return node
[ "def", "make_node", "(", "clss", ",", "node", ",", "*", "params", ")", ":", "if", "node", "is", "None", ":", "node", "=", "clss", "(", ")", "if", "node", ".", "token", "!=", "'PARAMLIST'", ":", "return", "clss", ".", "make_node", "(", "None", ",", "node", ",", "*", "params", ")", "for", "i", "in", "params", ":", "if", "i", "is", "not", "None", ":", "node", ".", "appendChild", "(", "i", ")", "return", "node" ]
This will return a node with a param_list (declared in a function declaration) Parameters: -node: A SymbolPARAMLIST instance or None -params: SymbolPARAMDECL insances
[ "This", "will", "return", "a", "node", "with", "a", "param_list", "(", "declared", "in", "a", "function", "declaration", ")", "Parameters", ":", "-", "node", ":", "A", "SymbolPARAMLIST", "instance", "or", "None", "-", "params", ":", "SymbolPARAMDECL", "insances" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/paramlist.py#L32-L49
boriel/zxbasic
symbols/paramlist.py
SymbolPARAMLIST.appendChild
def appendChild(self, param): ''' Overrides base class. ''' Symbol.appendChild(self, param) if param.offset is None: param.offset = self.size self.size += param.size
python
def appendChild(self, param): ''' Overrides base class. ''' Symbol.appendChild(self, param) if param.offset is None: param.offset = self.size self.size += param.size
[ "def", "appendChild", "(", "self", ",", "param", ")", ":", "Symbol", ".", "appendChild", "(", "self", ",", "param", ")", "if", "param", ".", "offset", "is", "None", ":", "param", ".", "offset", "=", "self", ".", "size", "self", ".", "size", "+=", "param", ".", "size" ]
Overrides base class.
[ "Overrides", "base", "class", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/paramlist.py#L51-L57
boriel/zxbasic
symbols/binary.py
SymbolBINARY.make_node
def make_node(cls, operator, left, right, lineno, func=None, type_=None): """ Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right: right operand -func: is a lambda function used when constant folding is applied -type_: resulting type (to enforce it). If no type_ is specified the resulting one will be guessed. """ if left is None or right is None: return None a, b = left, right # short form names # Check for constant non-numeric operations c_type = common_type(a, b) # Resulting operation type or None if c_type: # there must be a common type for a and b if is_numeric(a, b) and (is_const(a) or is_number(a)) and \ (is_const(b) or is_number(b)): if func is not None: a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type return SymbolNUMBER(func(a.value, b.value), type_=type_, lineno=lineno) if is_static(a, b): a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type return SymbolCONST(cls(operator, a, b, lineno, type_=type_, func=func), lineno=lineno) if operator in ('BNOT', 'BAND', 'BOR', 'BXOR', 'NOT', 'AND', 'OR', 'XOR', 'MINUS', 'MULT', 'DIV', 'SHL', 'SHR') and \ not is_numeric(a, b): syntax_error(lineno, 'Operator %s cannot be used with STRINGS' % operator) return None if is_string(a, b) and func is not None: # Are they STRING Constants? if operator == 'PLUS': return SymbolSTRING(func(a.value, b.value), lineno) return SymbolNUMBER(int(func(a.text, b.text)), type_=TYPE.ubyte, lineno=lineno) # Convert to u8 (boolean) if operator in ('BNOT', 'BAND', 'BOR', 'BXOR'): if TYPE.is_decimal(c_type): c_type = TYPE.long_ if a.type_ != b.type_ and TYPE.string in (a.type_, b.type_): c_type = a.type_ # Will give an error based on the fist operand if operator not in ('SHR', 'SHL'): a = SymbolTYPECAST.make_node(c_type, a, lineno) b = SymbolTYPECAST.make_node(c_type, b, lineno) if a is None or b is None: return None if type_ is None: if operator in ('LT', 'GT', 'EQ', 'LE', 'GE', 'NE', 'AND', 'OR', 'XOR', 'NOT'): type_ = TYPE.ubyte # Boolean type else: type_ = c_type return cls(operator, a, b, type_=type_, lineno=lineno)
python
def make_node(cls, operator, left, right, lineno, func=None, type_=None): """ Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right: right operand -func: is a lambda function used when constant folding is applied -type_: resulting type (to enforce it). If no type_ is specified the resulting one will be guessed. """ if left is None or right is None: return None a, b = left, right # short form names # Check for constant non-numeric operations c_type = common_type(a, b) # Resulting operation type or None if c_type: # there must be a common type for a and b if is_numeric(a, b) and (is_const(a) or is_number(a)) and \ (is_const(b) or is_number(b)): if func is not None: a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type return SymbolNUMBER(func(a.value, b.value), type_=type_, lineno=lineno) if is_static(a, b): a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type return SymbolCONST(cls(operator, a, b, lineno, type_=type_, func=func), lineno=lineno) if operator in ('BNOT', 'BAND', 'BOR', 'BXOR', 'NOT', 'AND', 'OR', 'XOR', 'MINUS', 'MULT', 'DIV', 'SHL', 'SHR') and \ not is_numeric(a, b): syntax_error(lineno, 'Operator %s cannot be used with STRINGS' % operator) return None if is_string(a, b) and func is not None: # Are they STRING Constants? if operator == 'PLUS': return SymbolSTRING(func(a.value, b.value), lineno) return SymbolNUMBER(int(func(a.text, b.text)), type_=TYPE.ubyte, lineno=lineno) # Convert to u8 (boolean) if operator in ('BNOT', 'BAND', 'BOR', 'BXOR'): if TYPE.is_decimal(c_type): c_type = TYPE.long_ if a.type_ != b.type_ and TYPE.string in (a.type_, b.type_): c_type = a.type_ # Will give an error based on the fist operand if operator not in ('SHR', 'SHL'): a = SymbolTYPECAST.make_node(c_type, a, lineno) b = SymbolTYPECAST.make_node(c_type, b, lineno) if a is None or b is None: return None if type_ is None: if operator in ('LT', 'GT', 'EQ', 'LE', 'GE', 'NE', 'AND', 'OR', 'XOR', 'NOT'): type_ = TYPE.ubyte # Boolean type else: type_ = c_type return cls(operator, a, b, type_=type_, lineno=lineno)
[ "def", "make_node", "(", "cls", ",", "operator", ",", "left", ",", "right", ",", "lineno", ",", "func", "=", "None", ",", "type_", "=", "None", ")", ":", "if", "left", "is", "None", "or", "right", "is", "None", ":", "return", "None", "a", ",", "b", "=", "left", ",", "right", "# short form names", "# Check for constant non-numeric operations", "c_type", "=", "common_type", "(", "a", ",", "b", ")", "# Resulting operation type or None", "if", "c_type", ":", "# there must be a common type for a and b", "if", "is_numeric", "(", "a", ",", "b", ")", "and", "(", "is_const", "(", "a", ")", "or", "is_number", "(", "a", ")", ")", "and", "(", "is_const", "(", "b", ")", "or", "is_number", "(", "b", ")", ")", ":", "if", "func", "is", "not", "None", ":", "a", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "a", ",", "lineno", ")", "# ensure type", "b", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "b", ",", "lineno", ")", "# ensure type", "return", "SymbolNUMBER", "(", "func", "(", "a", ".", "value", ",", "b", ".", "value", ")", ",", "type_", "=", "type_", ",", "lineno", "=", "lineno", ")", "if", "is_static", "(", "a", ",", "b", ")", ":", "a", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "a", ",", "lineno", ")", "# ensure type", "b", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "b", ",", "lineno", ")", "# ensure type", "return", "SymbolCONST", "(", "cls", "(", "operator", ",", "a", ",", "b", ",", "lineno", ",", "type_", "=", "type_", ",", "func", "=", "func", ")", ",", "lineno", "=", "lineno", ")", "if", "operator", "in", "(", "'BNOT'", ",", "'BAND'", ",", "'BOR'", ",", "'BXOR'", ",", "'NOT'", ",", "'AND'", ",", "'OR'", ",", "'XOR'", ",", "'MINUS'", ",", "'MULT'", ",", "'DIV'", ",", "'SHL'", ",", "'SHR'", ")", "and", "not", "is_numeric", "(", "a", ",", "b", ")", ":", "syntax_error", "(", "lineno", ",", "'Operator %s cannot be used with STRINGS'", "%", "operator", ")", "return", "None", "if", "is_string", "(", "a", ",", "b", ")", "and", "func", "is", "not", "None", ":", "# Are they STRING Constants?", "if", "operator", "==", "'PLUS'", ":", "return", "SymbolSTRING", "(", "func", "(", "a", ".", "value", ",", "b", ".", "value", ")", ",", "lineno", ")", "return", "SymbolNUMBER", "(", "int", "(", "func", "(", "a", ".", "text", ",", "b", ".", "text", ")", ")", ",", "type_", "=", "TYPE", ".", "ubyte", ",", "lineno", "=", "lineno", ")", "# Convert to u8 (boolean)", "if", "operator", "in", "(", "'BNOT'", ",", "'BAND'", ",", "'BOR'", ",", "'BXOR'", ")", ":", "if", "TYPE", ".", "is_decimal", "(", "c_type", ")", ":", "c_type", "=", "TYPE", ".", "long_", "if", "a", ".", "type_", "!=", "b", ".", "type_", "and", "TYPE", ".", "string", "in", "(", "a", ".", "type_", ",", "b", ".", "type_", ")", ":", "c_type", "=", "a", ".", "type_", "# Will give an error based on the fist operand", "if", "operator", "not", "in", "(", "'SHR'", ",", "'SHL'", ")", ":", "a", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "a", ",", "lineno", ")", "b", "=", "SymbolTYPECAST", ".", "make_node", "(", "c_type", ",", "b", ",", "lineno", ")", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "if", "type_", "is", "None", ":", "if", "operator", "in", "(", "'LT'", ",", "'GT'", ",", "'EQ'", ",", "'LE'", ",", "'GE'", ",", "'NE'", ",", "'AND'", ",", "'OR'", ",", "'XOR'", ",", "'NOT'", ")", ":", "type_", "=", "TYPE", ".", "ubyte", "# Boolean type", "else", ":", "type_", "=", "c_type", "return", "cls", "(", "operator", ",", "a", ",", "b", ",", "type_", "=", "type_", ",", "lineno", "=", "lineno", ")" ]
Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right: right operand -func: is a lambda function used when constant folding is applied -type_: resulting type (to enforce it). If no type_ is specified the resulting one will be guessed.
[ "Creates", "a", "binary", "node", "for", "a", "binary", "operation", "e", ".", "g", ".", "A", "+", "6", "=", ">", "+", "(", "A", "6", ")", "in", "prefix", "notation", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/binary.py#L68-L135
boriel/zxbasic
symbols/type_.py
SymbolTYPE.is_dynamic
def is_dynamic(self): """ True if this type uses dynamic (Heap) memory. e.g. strings or dynamic arrays """ if self is not self.final: return self.final.is_dynamic return any([x.is_dynamic for x in self.children])
python
def is_dynamic(self): """ True if this type uses dynamic (Heap) memory. e.g. strings or dynamic arrays """ if self is not self.final: return self.final.is_dynamic return any([x.is_dynamic for x in self.children])
[ "def", "is_dynamic", "(", "self", ")", ":", "if", "self", "is", "not", "self", ".", "final", ":", "return", "self", ".", "final", ".", "is_dynamic", "return", "any", "(", "[", "x", ".", "is_dynamic", "for", "x", "in", "self", ".", "children", "]", ")" ]
True if this type uses dynamic (Heap) memory. e.g. strings or dynamic arrays
[ "True", "if", "this", "type", "uses", "dynamic", "(", "Heap", ")", "memory", ".", "e", ".", "g", ".", "strings", "or", "dynamic", "arrays" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/type_.py#L65-L72
boriel/zxbasic
symbols/type_.py
Type.to_signed
def to_signed(cls, t): """ Return signed type or equivalent """ assert isinstance(t, SymbolTYPE) t = t.final assert t.is_basic if cls.is_unsigned(t): return {cls.ubyte: cls.byte_, cls.uinteger: cls.integer, cls.ulong: cls.long_}[t] if cls.is_signed(t) or cls.is_decimal(t): return t return cls.unknown
python
def to_signed(cls, t): """ Return signed type or equivalent """ assert isinstance(t, SymbolTYPE) t = t.final assert t.is_basic if cls.is_unsigned(t): return {cls.ubyte: cls.byte_, cls.uinteger: cls.integer, cls.ulong: cls.long_}[t] if cls.is_signed(t) or cls.is_decimal(t): return t return cls.unknown
[ "def", "to_signed", "(", "cls", ",", "t", ")", ":", "assert", "isinstance", "(", "t", ",", "SymbolTYPE", ")", "t", "=", "t", ".", "final", "assert", "t", ".", "is_basic", "if", "cls", ".", "is_unsigned", "(", "t", ")", ":", "return", "{", "cls", ".", "ubyte", ":", "cls", ".", "byte_", ",", "cls", ".", "uinteger", ":", "cls", ".", "integer", ",", "cls", ".", "ulong", ":", "cls", ".", "long_", "}", "[", "t", "]", "if", "cls", ".", "is_signed", "(", "t", ")", "or", "cls", ".", "is_decimal", "(", "t", ")", ":", "return", "t", "return", "cls", ".", "unknown" ]
Return signed type or equivalent
[ "Return", "signed", "type", "or", "equivalent" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/type_.py#L325-L337
boriel/zxbasic
api/symboltable.py
SymbolTable.get_entry
def get_entry(self, id_, 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
python
def get_entry(self, id_, 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
[ "def", "get_entry", "(", "self", ",", "id_", ",", "scope", "=", "None", ")", ":", "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" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L147-L163
boriel/zxbasic
api/symboltable.py
SymbolTable.declare
def declare(self, id_, lineno, 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
python
def declare(self, id_, lineno, 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
[ "def", "declare", "(", "self", ",", "id_", ",", "lineno", ",", "entry", ")", ":", "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" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L165-L202
boriel/zxbasic
api/symboltable.py
SymbolTable.check_is_declared
def check_is_declared(self, id_, lineno, 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
python
def check_is_declared(self, id_, lineno, 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_declared", "(", "self", ",", "id_", ",", "lineno", ",", "classname", "=", "'identifier'", ",", "scope", "=", "None", ",", "show_error", "=", "True", ")", ":", "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" ]
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.
[ "Checks", "if", "the", "given", "id", "is", "already", "defined", "in", "any", "scope", "or", "raises", "a", "Syntax", "Error", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L207-L223
boriel/zxbasic
api/symboltable.py
SymbolTable.check_is_undeclared
def check_is_undeclared(self, id_, lineno, 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
python
def check_is_undeclared(self, id_, lineno, 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_is_undeclared", "(", "self", ",", "id_", ",", "lineno", ",", "classname", "=", "'identifier'", ",", "scope", "=", "None", ",", "show_error", "=", "False", ")", ":", "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" ]
The reverse of the above. Check the given identifier is not already declared. Returns True if OK, False otherwise.
[ "The", "reverse", "of", "the", "above", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L225-L244
boriel/zxbasic
api/symboltable.py
SymbolTable.check_class
def check_class(self, id_, class_, lineno, 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
python
def check_class(self, id_, class_, lineno, 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
[ "def", "check_class", "(", "self", ",", "id_", ",", "class_", ",", "lineno", ",", "scope", "=", "None", ",", "show_error", "=", "True", ")", ":", "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" ]
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.
[ "Check", "the", "id", "is", "either", "undefined", "or", "defined", "with", "the", "given", "class", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L246-L277
boriel/zxbasic
api/symboltable.py
SymbolTable.enter_scope
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 = []
python
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 = []
[ "def", "enter_scope", "(", "self", ",", "funcname", ")", ":", "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", "=", "[", "]" ]
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).
[ "Starts", "a", "new", "variable", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L282-L292
boriel/zxbasic
api/symboltable.py
SymbolTable.leave_scope
def leave_scope(self): """ Ends a function body and pops current scope out of the symbol table. """ def entry_size(entry): """ For local variables and params, returns the real variable or local array size in bytes """ if entry.scope == SCOPE.global_ or \ entry.is_aliased: # aliases or global variables = 0 return 0 if entry.class_ != CLASS.array: return entry.size return entry.memsize 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! warning_not_used(v.lineno, v.name, kind=kind) entries = sorted(self.table[self.current_scope].values(filter_by_opt=True), key=entry_size) offset = 0 for entry in entries: # Symbols of the current level if entry.class_ is CLASS.unknown: self.move_to_global_scope(entry.name) 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 self.mangle = self[self.current_scope].parent_mangle self.table.pop() global_.LOOPS = global_.META_LOOPS.pop() return offset
python
def leave_scope(self): """ Ends a function body and pops current scope out of the symbol table. """ def entry_size(entry): """ For local variables and params, returns the real variable or local array size in bytes """ if entry.scope == SCOPE.global_ or \ entry.is_aliased: # aliases or global variables = 0 return 0 if entry.class_ != CLASS.array: return entry.size return entry.memsize 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! warning_not_used(v.lineno, v.name, kind=kind) entries = sorted(self.table[self.current_scope].values(filter_by_opt=True), key=entry_size) offset = 0 for entry in entries: # Symbols of the current level if entry.class_ is CLASS.unknown: self.move_to_global_scope(entry.name) 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 self.mangle = self[self.current_scope].parent_mangle self.table.pop() global_.LOOPS = global_.META_LOOPS.pop() return offset
[ "def", "leave_scope", "(", "self", ")", ":", "def", "entry_size", "(", "entry", ")", ":", "\"\"\" For local variables and params, returns the real variable or\n local array size in bytes\n \"\"\"", "if", "entry", ".", "scope", "==", "SCOPE", ".", "global_", "or", "entry", ".", "is_aliased", ":", "# aliases or global variables = 0", "return", "0", "if", "entry", ".", "class_", "!=", "CLASS", ".", "array", ":", "return", "entry", ".", "size", "return", "entry", ".", "memsize", "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!", "warning_not_used", "(", "v", ".", "lineno", ",", "v", ".", "name", ",", "kind", "=", "kind", ")", "entries", "=", "sorted", "(", "self", ".", "table", "[", "self", ".", "current_scope", "]", ".", "values", "(", "filter_by_opt", "=", "True", ")", ",", "key", "=", "entry_size", ")", "offset", "=", "0", "for", "entry", "in", "entries", ":", "# Symbols of the current level", "if", "entry", ".", "class_", "is", "CLASS", ".", "unknown", ":", "self", ".", "move_to_global_scope", "(", "entry", ".", "name", ")", "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", "self", ".", "mangle", "=", "self", "[", "self", ".", "current_scope", "]", ".", "parent_mangle", "self", ".", "table", ".", "pop", "(", ")", "global_", ".", "LOOPS", "=", "global_", ".", "META_LOOPS", ".", "pop", "(", ")", "return", "offset" ]
Ends a function body and pops current scope out of the symbol table.
[ "Ends", "a", "function", "body", "and", "pops", "current", "scope", "out", "of", "the", "symbol", "table", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L294-L345
boriel/zxbasic
api/symboltable.py
SymbolTable.move_to_global_scope
def move_to_global_scope(self, id_): """ 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_))
python
def move_to_global_scope(self, id_): """ 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", "move_to_global_scope", "(", "self", ",", "id_", ")", ":", "# 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_", ")", ")" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L347-L362
boriel/zxbasic
api/symboltable.py
SymbolTable.make_static
def make_static(self, id_): """ 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
python
def make_static(self, id_): """ 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
[ "def", "make_static", "(", "self", ",", "id_", ")", ":", "entry", "=", "self", ".", "table", "[", "self", ".", "current_scope", "]", "[", "id_", "]", "entry", ".", "scope", "=", "SCOPE", ".", "global_", "self", ".", "table", "[", "self", ".", "global_scope", "]", "[", "entry", ".", "mangled", "]", "=", "entry" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L364-L376
boriel/zxbasic
api/symboltable.py
SymbolTable.access_id
def access_id(self, id_, lineno, 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
python
def access_id(self, id_, lineno, 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_id", "(", "self", ",", "id_", ",", "lineno", ",", "scope", "=", "None", ",", "default_type", "=", "None", ",", "default_class", "=", "CLASS", ".", "unknown", ")", ":", "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" ]
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
[ "Access", "a", "symbol", "by", "its", "identifier", "and", "checks", "if", "it", "exists", ".", "If", "not", "it", "s", "supposed", "to", "be", "an", "implicit", "declared", "variable", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L390-L420
boriel/zxbasic
api/symboltable.py
SymbolTable.access_var
def access_var(self, id_, lineno, 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
python
def access_var(self, id_, lineno, 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_var", "(", "self", ",", "id_", ",", "lineno", ",", "scope", "=", "None", ",", "default_type", "=", "None", ")", ":", "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" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L422-L444
boriel/zxbasic
api/symboltable.py
SymbolTable.access_array
def access_array(self, id_, lineno, 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)
python
def access_array(self, id_, lineno, 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_array", "(", "self", ",", "id_", ",", "lineno", ",", "scope", "=", "None", ",", "default_type", "=", "None", ")", ":", "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", ")" ]
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.
[ "Called", "whenever", "an", "accessed", "variable", "is", "expected", "to", "be", "an", "array", ".", "ZX", "BASIC", "requires", "arrays", "to", "be", "declared", "before", "usage", "so", "they", "re", "checked", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L446-L460
boriel/zxbasic
api/symboltable.py
SymbolTable.access_func
def access_func(self, id_, lineno, 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
python
def access_func(self, id_, lineno, 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_func", "(", "self", ",", "id_", ",", "lineno", ",", "scope", "=", "None", ",", "default_type", "=", "None", ")", ":", "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" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L462-L484
boriel/zxbasic
api/symboltable.py
SymbolTable.access_call
def access_call(self, id_, lineno, 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
python
def access_call(self, id_, lineno, 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_call", "(", "self", ",", "id_", ",", "lineno", ",", "scope", "=", "None", ",", "type_", "=", "None", ")", ":", "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" ]
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.
[ "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", ":" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L486-L517
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_variable
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 # type_ = entry.type_ # TODO: Unused?? 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
python
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 # type_ = entry.type_ # TODO: Unused?? 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_variable", "(", "self", ",", "id_", ",", "lineno", ",", "type_", ",", "default_value", "=", "None", ")", ":", "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", "# type_ = entry.type_ # TODO: Unused??", "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" ]
Like the above, but checks that entry.declared is False. Otherwise raises an error. Parameter default_value specifies an initialized variable, if set.
[ "Like", "the", "above", "but", "checks", "that", "entry", ".", "declared", "is", "False", ".", "Otherwise", "raises", "an", "error", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L534-L594
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_type
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
python
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_type", "(", "self", ",", "type_", ")", ":", "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" ]
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.
[ "Declares", "a", "type", ".", "Checks", "its", "name", "is", "not", "already", "used", "in", "the", "current", "scope", "and", "that", "it", "s", "not", "a", "basic", "type", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L596-L614
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_const
def declare_const(self, id_, lineno, 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
python
def declare_const(self, id_, lineno, 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_const", "(", "self", ",", "id_", ",", "lineno", ",", "type_", ",", "default_value", ")", ":", "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" ]
Similar to the above. But declares a Constant.
[ "Similar", "to", "the", "above", ".", "But", "declares", "a", "Constant", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L616-L635
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_label
def declare_label(self, id_, lineno): """ 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
python
def declare_label(self, id_, lineno): """ 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_label", "(", "self", ",", "id_", ",", "lineno", ")", ":", "# 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" ]
Declares a label (line numbers are also labels). Unlike variables, labels are always global.
[ "Declares", "a", "label", "(", "line", "numbers", "are", "also", "labels", ")", ".", "Unlike", "variables", "labels", "are", "always", "global", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L637-L686
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_param
def declare_param(self, id_, lineno, type_=None): """ 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 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
python
def declare_param(self, id_, lineno, type_=None): """ 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 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_param", "(", "self", ",", "id_", ",", "lineno", ",", "type_", "=", "None", ")", ":", "if", "not", "self", ".", "check_is_undeclared", "(", "id_", ",", "lineno", ",", "classname", "=", "'parameter'", ",", "scope", "=", "self", ".", "current_scope", ",", "show_error", "=", "True", ")", ":", "return", "None", "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" ]
Declares a parameter Check if entry.declared is False. Otherwise raises an error.
[ "Declares", "a", "parameter", "Check", "if", "entry", ".", "declared", "is", "False", ".", "Otherwise", "raises", "an", "error", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L688-L702
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_array
def declare_array(self, id_, lineno, type_, bounds, default_value=None): """ Declares an array in the symbol table (VARARRAY). Error if already exists. """ 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.lbound_used = entry.ubound_used = False # Flag to true when LBOUND/UBOUND used somewhere in the code __DEBUG__('Entry %s declared with class %s at scope %i' % (id_, CLASS.to_string(entry.class_), self.current_scope)) return entry
python
def declare_array(self, id_, lineno, type_, bounds, default_value=None): """ Declares an array in the symbol table (VARARRAY). Error if already exists. """ 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.lbound_used = entry.ubound_used = False # Flag to true when LBOUND/UBOUND used somewhere in the code __DEBUG__('Entry %s declared with class %s at scope %i' % (id_, CLASS.to_string(entry.class_), self.current_scope)) return entry
[ "def", "declare_array", "(", "self", ",", "id_", ",", "lineno", ",", "type_", ",", "bounds", ",", "default_value", "=", "None", ")", ":", "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", ".", "lbound_used", "=", "entry", ".", "ubound_used", "=", "False", "# Flag to true when LBOUND/UBOUND used somewhere in the code", "__DEBUG__", "(", "'Entry %s declared with class %s at scope %i'", "%", "(", "id_", ",", "CLASS", ".", "to_string", "(", "entry", ".", "class_", ")", ",", "self", ".", "current_scope", ")", ")", "return", "entry" ]
Declares an array in the symbol table (VARARRAY). Error if already exists.
[ "Declares", "an", "array", "in", "the", "symbol", "table", "(", "VARARRAY", ")", ".", "Error", "if", "already", "exists", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L704-L760
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_func
def declare_func(self, id_, lineno, 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
python
def declare_func(self, id_, lineno, 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", "declare_func", "(", "self", ",", "id_", ",", "lineno", ",", "type_", "=", "None", ")", ":", "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" ]
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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L762-L804
boriel/zxbasic
api/symboltable.py
SymbolTable.check_labels
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)
python
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_labels", "(", "self", ")", ":", "for", "entry", "in", "self", ".", "labels", ":", "self", ".", "check_is_declared", "(", "entry", ".", "name", ",", "entry", ".", "lineno", ",", "CLASS", ".", "label", ")" ]
Checks if all the labels has been declared
[ "Checks", "if", "all", "the", "labels", "has", "been", "declared" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L806-L810
boriel/zxbasic
api/symboltable.py
SymbolTable.check_classes
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)
python
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)
[ "def", "check_classes", "(", "self", ",", "scope", "=", "-", "1", ")", ":", "for", "entry", "in", "self", "[", "scope", "]", ".", "values", "(", ")", ":", "if", "entry", ".", "class_", "is", "None", ":", "syntax_error", "(", "entry", ".", "lineno", ",", "\"Unknown identifier '%s'\"", "%", "entry", ".", "name", ")" ]
Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked.
[ "Check", "if", "pending", "identifiers", "are", "defined", "or", "not", ".", "If", "not", "returns", "a", "syntax", "error", ".", "If", "no", "scope", "is", "given", "the", "current", "one", "is", "checked", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L812-L819
boriel/zxbasic
api/symboltable.py
SymbolTable.vars_
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]
python
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]
[ "def", "vars_", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "var", "]" ]
Returns symbol instances corresponding to variables of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "variables", "of", "the", "current", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L825-L829
boriel/zxbasic
api/symboltable.py
SymbolTable.labels
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]
python
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]
[ "def", "labels", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "label", "]" ]
Returns symbol instances corresponding to labels in the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "labels", "in", "the", "current", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L832-L836
boriel/zxbasic
api/symboltable.py
SymbolTable.types
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)]
python
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)]
[ "def", "types", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "isinstance", "(", "x", ",", "symbols", ".", "TYPE", ")", "]" ]
Returns symbol instances corresponding to type declarations within the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "type", "declarations", "within", "the", "current", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L839-L843
boriel/zxbasic
api/symboltable.py
SymbolTable.arrays
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]
python
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]
[ "def", "arrays", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "array", "]" ]
Returns symbol instances corresponding to arrays of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "arrays", "of", "the", "current", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L846-L850
boriel/zxbasic
api/symboltable.py
SymbolTable.functions
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)]
python
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)]
[ "def", "functions", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "in", "(", "CLASS", ".", "function", ",", "CLASS", ".", "sub", ")", "]" ]
Returns symbol instances corresponding to functions of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "functions", "of", "the", "current", "scope", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L853-L858
boriel/zxbasic
api/symboltable.py
SymbolTable.aliases
def aliases(self): """ Returns symbol instances corresponding to aliased vars. """ return [x for x in self[self.current_scope].values() if x.is_aliased]
python
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", "aliases", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "is_aliased", "]" ]
Returns symbol instances corresponding to aliased vars.
[ "Returns", "symbol", "instances", "corresponding", "to", "aliased", "vars", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L861-L864
boriel/zxbasic
api/check.py
check_type
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: syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" % (arg.type_, type_list[0])) else: syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'" % (arg.type_, tuple(type_list))) return False
python
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: syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" % (arg.type_, type_list[0])) else: syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'" % (arg.type_, tuple(type_list))) return False
[ "def", "check_type", "(", "lineno", ",", "type_list", ",", "arg", ")", ":", "if", "not", "isinstance", "(", "type_list", ",", "list", ")", ":", "type_list", "=", "[", "type_list", "]", "if", "arg", ".", "type_", "in", "type_list", ":", "return", "True", "if", "len", "(", "type_list", ")", "==", "1", ":", "syntax_error", "(", "lineno", ",", "\"Wrong expression type '%s'. Expected '%s'\"", "%", "(", "arg", ".", "type_", ",", "type_list", "[", "0", "]", ")", ")", "else", ":", "syntax_error", "(", "lineno", ",", "\"Wrong expression type '%s'. Expected one of '%s'\"", "%", "(", "arg", ".", "type_", ",", "tuple", "(", "type_list", ")", ")", ")", "return", "False" ]
Check arg's type is one in type_list, otherwise, raises an error.
[ "Check", "arg", "s", "type", "is", "one", "in", "type_list", "otherwise", "raises", "an", "error", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L44-L61
boriel/zxbasic
api/check.py
check_is_declared_explicit
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
python
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
[ "def", "check_is_declared_explicit", "(", "lineno", ",", "id_", ",", "classname", "=", "'variable'", ")", ":", "if", "not", "config", ".", "OPTIONS", ".", "explicit", ".", "value", ":", "return", "True", "entry", "=", "global_", ".", "SYMBOL_TABLE", ".", "check_is_declared", "(", "id_", ",", "lineno", ",", "classname", ")", "return", "entry", "is", "not", "None" ]
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.
[ "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", ")", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L64-L76
boriel/zxbasic
api/check.py
check_call_arguments
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 '' syntax_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 not arg.typecast(param.type_): return False if param.byref: from symbols.var import SymbolVAR if not isinstance(arg.value, SymbolVAR): syntax_error(lineno, "Expected a variable name, not an " "expression (parameter By Reference)") return False if arg.class_ not in (CLASS.var, CLASS.array): syntax_error(lineno, "Expected a variable or array name " "(parameter By Reference)") return False arg.byref = True if entry.forwarded: # The function / sub was DECLARED but not implemented syntax_error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name)) return False return True
python
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 '' syntax_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 not arg.typecast(param.type_): return False if param.byref: from symbols.var import SymbolVAR if not isinstance(arg.value, SymbolVAR): syntax_error(lineno, "Expected a variable name, not an " "expression (parameter By Reference)") return False if arg.class_ not in (CLASS.var, CLASS.array): syntax_error(lineno, "Expected a variable or array name " "(parameter By Reference)") return False arg.byref = True if entry.forwarded: # The function / sub was DECLARED but not implemented syntax_error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name)) return False return True
[ "def", "check_call_arguments", "(", "lineno", ",", "id_", ",", "args", ")", ":", "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", "''", "syntax_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", "not", "arg", ".", "typecast", "(", "param", ".", "type_", ")", ":", "return", "False", "if", "param", ".", "byref", ":", "from", "symbols", ".", "var", "import", "SymbolVAR", "if", "not", "isinstance", "(", "arg", ".", "value", ",", "SymbolVAR", ")", ":", "syntax_error", "(", "lineno", ",", "\"Expected a variable name, not an \"", "\"expression (parameter By Reference)\"", ")", "return", "False", "if", "arg", ".", "class_", "not", "in", "(", "CLASS", ".", "var", ",", "CLASS", ".", "array", ")", ":", "syntax_error", "(", "lineno", ",", "\"Expected a variable or array name \"", "\"(parameter By Reference)\"", ")", "return", "False", "arg", ".", "byref", "=", "True", "if", "entry", ".", "forwarded", ":", "# The function / sub was DECLARED but not implemented", "syntax_error", "(", "lineno", ",", "\"%s '%s' declared but not implemented\"", "%", "(", "CLASS", ".", "to_string", "(", "entry", ".", "class_", ")", ",", "entry", ".", "name", ")", ")", "return", "False", "return", "True" ]
Check arguments against function signature. Checks every argument in a function call against a function. Returns True on success.
[ "Check", "arguments", "against", "function", "signature", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L87-L129
boriel/zxbasic
api/check.py
check_pending_calls
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 (parametres, etc) for id_, params, lineno in global_.FUNCTION_CALLS: result = result and check_call_arguments(lineno, id_, params) return result
python
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 (parametres, etc) for id_, params, lineno in global_.FUNCTION_CALLS: result = result and check_call_arguments(lineno, id_, params) return result
[ "def", "check_pending_calls", "(", ")", ":", "result", "=", "True", "# Check for functions defined after calls (parametres, etc)", "for", "id_", ",", "params", ",", "lineno", "in", "global_", ".", "FUNCTION_CALLS", ":", "result", "=", "result", "and", "check_call_arguments", "(", "lineno", ",", "id_", ",", "params", ")", "return", "result" ]
Calls the above function for each pending call of the current scope level
[ "Calls", "the", "above", "function", "for", "each", "pending", "call", "of", "the", "current", "scope", "level" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L132-L142
boriel/zxbasic
api/check.py
check_pending_labels
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: syntax_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
python
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: syntax_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_pending_labels", "(", "ast", ")", ":", "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", ":", "syntax_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" ]
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.
[ "Iteratively", "traverses", "the", "node", "looking", "for", "ID", "with", "no", "class", "set", "marks", "them", "as", "labels", "and", "check", "they", "ve", "been", "declared", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L145-L178
boriel/zxbasic
api/check.py
check_and_make_label
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: syntax_error(lineno, 'Line numbers must be integers.') return None else: id_ = lbl return global_.SYMBOL_TABLE.access_label(id_, lineno)
python
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: syntax_error(lineno, 'Line numbers must be integers.') return None else: id_ = lbl return global_.SYMBOL_TABLE.access_label(id_, lineno)
[ "def", "check_and_make_label", "(", "lbl", ",", "lineno", ")", ":", "if", "isinstance", "(", "lbl", ",", "float", ")", ":", "if", "lbl", "==", "int", "(", "lbl", ")", ":", "id_", "=", "str", "(", "int", "(", "lbl", ")", ")", "else", ":", "syntax_error", "(", "lineno", ",", "'Line numbers must be integers.'", ")", "return", "None", "else", ":", "id_", "=", "lbl", "return", "global_", ".", "SYMBOL_TABLE", ".", "access_label", "(", "id_", ",", "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.
[ "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", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L181-L197
boriel/zxbasic
api/check.py
is_null
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
python
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_null", "(", "*", "symbols", ")", ":", "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" ]
True if no nodes or all the given nodes are either None, NOP or empty blocks. For blocks this applies recursively
[ "True", "if", "no", "nodes", "or", "all", "the", "given", "nodes", "are", "either", "None", "NOP", "or", "empty", "blocks", ".", "For", "blocks", "this", "applies", "recursively" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L203-L221
boriel/zxbasic
api/check.py
is_SYMBOL
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
python
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_SYMBOL", "(", "token", ",", "*", "symbols", ")", ":", "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" ]
Returns True if ALL of the given argument are AST nodes of the given token (e.g. 'BINARY')
[ "Returns", "True", "if", "ALL", "of", "the", "given", "argument", "are", "AST", "nodes", "of", "the", "given", "token", "(", "e", ".", "g", ".", "BINARY", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L224-L234
boriel/zxbasic
api/check.py
is_const
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)
python
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", ")", ":", "return", "is_SYMBOL", "(", "'VAR'", ",", "*", "p", ")", "and", "all", "(", "x", ".", "class_", "==", "CLASS", ".", "const", "for", "x", "in", "p", ")" ]
A constant in the program, like CONST a = 5
[ "A", "constant", "in", "the", "program", "like", "CONST", "a", "=", "5" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L245-L248
boriel/zxbasic
api/check.py
is_static
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)
python
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_static", "(", "*", "p", ")", ":", "return", "all", "(", "is_CONST", "(", "x", ")", "or", "is_number", "(", "x", ")", "or", "is_const", "(", "x", ")", "for", "x", "in", "p", ")" ]
A static value (does not change at runtime) which is known at compile time
[ "A", "static", "value", "(", "does", "not", "change", "at", "runtime", ")", "which", "is", "known", "at", "compile", "time" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L258-L265
boriel/zxbasic
api/check.py
is_number
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
python
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_number", "(", "*", "p", ")", ":", "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" ]
Returns True if ALL of the arguments are AST nodes containing NUMBER or numeric CONSTANTS
[ "Returns", "True", "if", "ALL", "of", "the", "arguments", "are", "AST", "nodes", "containing", "NUMBER", "or", "numeric", "CONSTANTS" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L268-L281
boriel/zxbasic
api/check.py
is_unsigned
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
python
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_unsigned", "(", "*", "p", ")", ":", "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" ]
Returns false unless all types in p are unsigned
[ "Returns", "false", "unless", "all", "types", "in", "p", "are", "unsigned" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L306-L320
boriel/zxbasic
api/check.py
is_type
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
python
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_type", "(", "type_", ",", "*", "p", ")", ":", "try", ":", "for", "i", "in", "p", ":", "if", "i", ".", "type_", "!=", "type_", ":", "return", "False", "return", "True", "except", ":", "pass", "return", "False" ]
True if all args have the same type
[ "True", "if", "all", "args", "have", "the", "same", "type" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L357-L369
boriel/zxbasic
api/check.py
is_dynamic
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
python
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_dynamic", "(", "*", "p", ")", ":", "# TODO: Explain this better", "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" ]
True if all args are dynamic (e.g. Strings, dynamic arrays, etc) The use a ptr (ref) and it might change during runtime.
[ "True", "if", "all", "args", "are", "dynamic", "(", "e", ".", "g", ".", "Strings", "dynamic", "arrays", "etc", ")", "The", "use", "a", "ptr", "(", "ref", ")", "and", "it", "might", "change", "during", "runtime", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L372-L388
boriel/zxbasic
api/check.py
is_callable
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)
python
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_callable", "(", "*", "p", ")", ":", "import", "symbols", "return", "all", "(", "isinstance", "(", "x", ",", "symbols", ".", "FUNCTION", ")", "for", "x", "in", "p", ")" ]
True if all the args are functions and / or subroutines
[ "True", "if", "all", "the", "args", "are", "functions", "and", "/", "or", "subroutines" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L391-L395
boriel/zxbasic
api/check.py
is_block_accessed
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
python
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_block_accessed", "(", "block", ")", ":", "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" ]
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
[ "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" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L398-L411
boriel/zxbasic
api/check.py
common_type
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
python
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
[ "def", "common_type", "(", "a", ",", "b", ")", ":", "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" ]
Returns a type which is common for both a and b types. Returns None if no common types allowed.
[ "Returns", "a", "type", "which", "is", "common", "for", "both", "a", "and", "b", "types", ".", "Returns", "None", "if", "no", "common", "types", "allowed", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L414-L463
boriel/zxbasic
zxb.py
output
def output(memory, ofile=None): """ Filters the output removing useless preprocessor #directives and writes it to the given file or to the screen if no file is passed """ for m in memory: m = m.rstrip('\r\n\t ') # Ensures no trailing newlines (might with upon includes) if m and m[0] == '#': # Preprocessor directive? if ofile is None: print(m) else: ofile.write('%s\n' % m) continue # Prints a 4 spaces "tab" for non labels if m and ':' not in m: if ofile is None: print(' '), else: ofile.write('\t') if ofile is None: print(m) else: ofile.write('%s\n' % m)
python
def output(memory, ofile=None): """ Filters the output removing useless preprocessor #directives and writes it to the given file or to the screen if no file is passed """ for m in memory: m = m.rstrip('\r\n\t ') # Ensures no trailing newlines (might with upon includes) if m and m[0] == '#': # Preprocessor directive? if ofile is None: print(m) else: ofile.write('%s\n' % m) continue # Prints a 4 spaces "tab" for non labels if m and ':' not in m: if ofile is None: print(' '), else: ofile.write('\t') if ofile is None: print(m) else: ofile.write('%s\n' % m)
[ "def", "output", "(", "memory", ",", "ofile", "=", "None", ")", ":", "for", "m", "in", "memory", ":", "m", "=", "m", ".", "rstrip", "(", "'\\r\\n\\t '", ")", "# Ensures no trailing newlines (might with upon includes)", "if", "m", "and", "m", "[", "0", "]", "==", "'#'", ":", "# Preprocessor directive?", "if", "ofile", "is", "None", ":", "print", "(", "m", ")", "else", ":", "ofile", ".", "write", "(", "'%s\\n'", "%", "m", ")", "continue", "# Prints a 4 spaces \"tab\" for non labels", "if", "m", "and", "':'", "not", "in", "m", ":", "if", "ofile", "is", "None", ":", "print", "(", "' '", ")", ",", "else", ":", "ofile", ".", "write", "(", "'\\t'", ")", "if", "ofile", "is", "None", ":", "print", "(", "m", ")", "else", ":", "ofile", ".", "write", "(", "'%s\\n'", "%", "m", ")" ]
Filters the output removing useless preprocessor #directives and writes it to the given file or to the screen if no file is passed
[ "Filters", "the", "output", "removing", "useless", "preprocessor", "#directives", "and", "writes", "it", "to", "the", "given", "file", "or", "to", "the", "screen", "if", "no", "file", "is", "passed" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxb.py#L48-L71
boriel/zxbasic
zxb.py
main
def main(args=None): """ Entry point when executed from command line. You can use zxb.py as a module with import, and this function won't be executed. """ api.config.init() zxbpp.init() zxbparser.init() arch.zx48k.backend.init() arch.zx48k.Translator.reset() asmparse.init() # ------------------------------------------------------------ # Command line parsing # ------------------------------------------------------------ parser = argparse.ArgumentParser(prog='zxb') parser.add_argument('PROGRAM', type=str, help='BASIC program file') parser.add_argument('-d', '--debug', dest='debug', default=OPTIONS.Debug.value, action='count', help='Enable verbosity/debugging output. Additional -d increase verbosity/debug level') parser.add_argument('-O', '--optimize', type=int, default=OPTIONS.optimization.value, help='Sets optimization level. ' '0 = None (default level is {0})'.format(OPTIONS.optimization.value)) parser.add_argument('-o', '--output', type=str, dest='output_file', default=None, help='Sets output file. Default is input filename with .bin extension') parser.add_argument('-T', '--tzx', action='store_true', help="Sets output format to tzx (default is .bin)") parser.add_argument('-t', '--tap', action='store_true', help="Sets output format to tap (default is .bin)") parser.add_argument('-B', '--BASIC', action='store_true', dest='basic', help="Creates a BASIC loader which loads the rest of the CODE. Requires -T ot -t") parser.add_argument('-a', '--autorun', action='store_true', help="Sets the program to be run once loaded") parser.add_argument('-A', '--asm', action='store_true', help="Sets output format to asm") parser.add_argument('-S', '--org', type=str, default=str(OPTIONS.org.value), help="Start of machine code. By default %i" % OPTIONS.org.value) parser.add_argument('-e', '--errmsg', type=str, dest='stderr', default=OPTIONS.StdErrFileName.value, help='Error messages file (standard error console by default)') parser.add_argument('--array-base', type=int, default=OPTIONS.array_base.value, help='Default lower index for arrays ({0} by default)'.format(OPTIONS.array_base.value)) parser.add_argument('--string-base', type=int, default=OPTIONS.string_base.value, help='Default lower index for strings ({0} by default)'.format(OPTIONS.array_base.value)) parser.add_argument('-Z', '--sinclair', action='store_true', help='Enable by default some more original ZX Spectrum Sinclair BASIC features: ATTR, SCREEN$, ' 'POINT') parser.add_argument('-H', '--heap-size', type=int, default=OPTIONS.heap_size.value, help='Sets heap size in bytes (default {0} bytes)'.format(OPTIONS.heap_size.value)) parser.add_argument('--debug-memory', action='store_true', help='Enables out-of-memory debug') parser.add_argument('--debug-array', action='store_true', help='Enables array boundary checking') parser.add_argument('--strict-bool', action='store_true', help='Enforce boolean values to be 0 or 1') parser.add_argument('--enable-break', action='store_true', help='Enables program execution BREAK detection') parser.add_argument('-E', '--emit-backend', action='store_true', help='Emits backend code instead of ASM or binary') parser.add_argument('--explicit', action='store_true', help='Requires all variables and functions to be declared before used') parser.add_argument('-D', '--define', type=str, dest='defines', action='append', help='Defines de given macro. Eg. -D MYDEBUG or -D NAME=Value') parser.add_argument('-M', '--mmap', type=str, dest='memory_map', default=None, help='Generate label memory map') parser.add_argument('-i', '--ignore-case', action='store_true', help='Ignore case. Makes variable names are case insensitive') parser.add_argument('-I', '--include-path', type=str, default='', help='Add colon separated list of directories to add to include path. e.g. -I dir1:dir2') parser.add_argument('--strict', action='store_true', help='Enables strict mode. Force explicit type declaration') parser.add_argument('--headerless', action='store_true', help='Header-less mode: omit asm prologue and epilogue') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(VERSION)) parser.add_argument('--parse-only', action='store_true', help='Only parses to check for syntax and semantic errors') parser.add_argument('--append-binary', default=[], action='append', help='Appends binary to tape file (only works with -t or -T)') parser.add_argument('--append-headless-binary', default=[], action='append', help='Appends binary to tape file (only works with -t or -T)') options = parser.parse_args(args=args) # ------------------------------------------------------------ # Setting of internal parameters according to command line # ------------------------------------------------------------ OPTIONS.Debug.value = options.debug OPTIONS.optimization.value = options.optimize OPTIONS.outputFileName.value = options.output_file OPTIONS.StdErrFileName.value = options.stderr OPTIONS.array_base.value = options.array_base OPTIONS.string_base.value = options.string_base OPTIONS.Sinclair.value = options.sinclair OPTIONS.heap_size.value = options.heap_size OPTIONS.memoryCheck.value = options.debug_memory OPTIONS.strictBool.value = options.strict_bool or OPTIONS.Sinclair.value OPTIONS.arrayCheck.value = options.debug_array OPTIONS.emitBackend.value = options.emit_backend OPTIONS.enableBreak.value = options.enable_break OPTIONS.explicit.value = options.explicit OPTIONS.memory_map.value = options.memory_map OPTIONS.strict.value = options.strict OPTIONS.headerless.value = options.headerless OPTIONS.org.value = api.utils.parse_int(options.org) if OPTIONS.org.value is None: parser.error("Invalid --org option '{}'".format(options.org)) if options.defines: for i in options.defines: name, val = tuple(i.split('=', 1)) OPTIONS.__DEFINES.value[name] = val zxbpp.ID_TABLE.define(name, lineno=0) if OPTIONS.Sinclair.value: OPTIONS.array_base.value = 1 OPTIONS.string_base.value = 1 OPTIONS.strictBool.value = True OPTIONS.case_insensitive.value = True if options.ignore_case: OPTIONS.case_insensitive.value = True debug.ENABLED = OPTIONS.Debug.value if int(options.tzx) + int(options.tap) + int(options.asm) + int(options.emit_backend) + \ int(options.parse_only) > 1: parser.error("Options --tap, --tzx, --emit-backend, --parse-only and --asm are mutually exclusive") return 3 if options.basic and not options.tzx and not options.tap: parser.error('Option --BASIC and --autorun requires --tzx or tap format') return 4 if options.append_binary and not options.tzx and not options.tap: parser.error('Option --append-binary needs either --tap or --tzx') return 5 OPTIONS.use_loader.value = options.basic OPTIONS.autorun.value = options.autorun if options.tzx: OPTIONS.output_file_type.value = 'tzx' elif options.tap: OPTIONS.output_file_type.value = 'tap' elif options.asm: OPTIONS.output_file_type.value = 'asm' elif options.emit_backend: OPTIONS.output_file_type.value = 'ic' args = [options.PROGRAM] if not os.path.exists(options.PROGRAM): parser.error("No such file or directory: '%s'" % args[0]) return 2 if OPTIONS.memoryCheck.value: OPTIONS.__DEFINES.value['__MEMORY_CHECK__'] = '' zxbpp.ID_TABLE.define('__MEMORY_CHECK__', lineno=0) if OPTIONS.arrayCheck.value: OPTIONS.__DEFINES.value['__CHECK_ARRAY_BOUNDARY__'] = '' zxbpp.ID_TABLE.define('__CHECK_ARRAY_BOUNDARY__', lineno=0) OPTIONS.include_path.value = options.include_path OPTIONS.inputFileName.value = zxbparser.FILENAME = \ os.path.basename(args[0]) 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_file(OPTIONS.StdErrFileName.value, 'wt', 'utf-8') zxbpp.setMode('basic') zxbpp.main(args) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors input_ = zxbpp.OUTPUT zxbparser.parser.parse(input_, lexer=zxblex.lexer, tracking=True, debug=(OPTIONS.Debug.value > 2)) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors # Optimizations optimizer = api.optimize.OptimizerVisitor() optimizer.visit(zxbparser.ast) # Emits intermediate code translator = arch.zx48k.Translator() translator.visit(zxbparser.ast) if gl.DATA_IS_USED: gl.FUNCTIONS.extend(gl.DATA_FUNCTIONS) # This will fill MEMORY with pending functions func_visitor = arch.zx48k.FunctionTranslator(gl.FUNCTIONS) func_visitor.start() # Emits data lines translator.emit_data_blocks() # Emits default constant strings translator.emit_strings() # Emits jump tables translator.emit_jump_tables() if OPTIONS.emitBackend.value: with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file: for quad in translator.dumpMemory(backend.MEMORY): output_file.write(str(quad) + '\n') backend.MEMORY[:] = [] # Empties memory # This will fill MEMORY with global declared variables translator = arch.zx48k.VarTranslator() translator.visit(zxbparser.data_ast) for quad in translator.dumpMemory(backend.MEMORY): output_file.write(str(quad) + '\n') return 0 # Exit success # Join all lines into a single string and ensures an INTRO at end of file asm_output = backend.emit(backend.MEMORY) asm_output = optimize(asm_output) + '\n' asm_output = asm_output.split('\n') for i in range(len(asm_output)): tmp = backend.ASMS.get(asm_output[i], None) if tmp is not None: asm_output[i] = '\n'.join(tmp) asm_output = '\n'.join(asm_output) # Now filter them against the preprocessor again zxbpp.setMode('asm') zxbpp.OUTPUT = '' zxbpp.filter_(asm_output, args[0]) # Now output the result asm_output = zxbpp.OUTPUT.split('\n') get_inits(asm_output) # Find out remaining inits backend.MEMORY[:] = [] # This will fill MEMORY with global declared variables translator = arch.zx48k.VarTranslator() translator.visit(zxbparser.data_ast) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors tmp = [x for x in backend.emit(backend.MEMORY) if x.strip()[0] != '#'] asm_output += tmp asm_output = backend.emit_start() + asm_output asm_output += backend.emit_end(asm_output) if options.asm: # Only output assembler file with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file: output(asm_output, output_file) elif not options.parse_only: fout = StringIO() output(asm_output, fout) asmparse.assemble(fout.getvalue()) fout.close() asmparse.generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type.value, binary_files=options.append_binary, headless_binary_files=options.append_headless_binary) if gl.has_errors: return 5 # Error in assembly if OPTIONS.memory_map.value: with open_file(OPTIONS.memory_map.value, 'wt', 'utf-8') as f: f.write(asmparse.MEMORY.memory_map) return gl.has_errors
python
def main(args=None): """ Entry point when executed from command line. You can use zxb.py as a module with import, and this function won't be executed. """ api.config.init() zxbpp.init() zxbparser.init() arch.zx48k.backend.init() arch.zx48k.Translator.reset() asmparse.init() # ------------------------------------------------------------ # Command line parsing # ------------------------------------------------------------ parser = argparse.ArgumentParser(prog='zxb') parser.add_argument('PROGRAM', type=str, help='BASIC program file') parser.add_argument('-d', '--debug', dest='debug', default=OPTIONS.Debug.value, action='count', help='Enable verbosity/debugging output. Additional -d increase verbosity/debug level') parser.add_argument('-O', '--optimize', type=int, default=OPTIONS.optimization.value, help='Sets optimization level. ' '0 = None (default level is {0})'.format(OPTIONS.optimization.value)) parser.add_argument('-o', '--output', type=str, dest='output_file', default=None, help='Sets output file. Default is input filename with .bin extension') parser.add_argument('-T', '--tzx', action='store_true', help="Sets output format to tzx (default is .bin)") parser.add_argument('-t', '--tap', action='store_true', help="Sets output format to tap (default is .bin)") parser.add_argument('-B', '--BASIC', action='store_true', dest='basic', help="Creates a BASIC loader which loads the rest of the CODE. Requires -T ot -t") parser.add_argument('-a', '--autorun', action='store_true', help="Sets the program to be run once loaded") parser.add_argument('-A', '--asm', action='store_true', help="Sets output format to asm") parser.add_argument('-S', '--org', type=str, default=str(OPTIONS.org.value), help="Start of machine code. By default %i" % OPTIONS.org.value) parser.add_argument('-e', '--errmsg', type=str, dest='stderr', default=OPTIONS.StdErrFileName.value, help='Error messages file (standard error console by default)') parser.add_argument('--array-base', type=int, default=OPTIONS.array_base.value, help='Default lower index for arrays ({0} by default)'.format(OPTIONS.array_base.value)) parser.add_argument('--string-base', type=int, default=OPTIONS.string_base.value, help='Default lower index for strings ({0} by default)'.format(OPTIONS.array_base.value)) parser.add_argument('-Z', '--sinclair', action='store_true', help='Enable by default some more original ZX Spectrum Sinclair BASIC features: ATTR, SCREEN$, ' 'POINT') parser.add_argument('-H', '--heap-size', type=int, default=OPTIONS.heap_size.value, help='Sets heap size in bytes (default {0} bytes)'.format(OPTIONS.heap_size.value)) parser.add_argument('--debug-memory', action='store_true', help='Enables out-of-memory debug') parser.add_argument('--debug-array', action='store_true', help='Enables array boundary checking') parser.add_argument('--strict-bool', action='store_true', help='Enforce boolean values to be 0 or 1') parser.add_argument('--enable-break', action='store_true', help='Enables program execution BREAK detection') parser.add_argument('-E', '--emit-backend', action='store_true', help='Emits backend code instead of ASM or binary') parser.add_argument('--explicit', action='store_true', help='Requires all variables and functions to be declared before used') parser.add_argument('-D', '--define', type=str, dest='defines', action='append', help='Defines de given macro. Eg. -D MYDEBUG or -D NAME=Value') parser.add_argument('-M', '--mmap', type=str, dest='memory_map', default=None, help='Generate label memory map') parser.add_argument('-i', '--ignore-case', action='store_true', help='Ignore case. Makes variable names are case insensitive') parser.add_argument('-I', '--include-path', type=str, default='', help='Add colon separated list of directories to add to include path. e.g. -I dir1:dir2') parser.add_argument('--strict', action='store_true', help='Enables strict mode. Force explicit type declaration') parser.add_argument('--headerless', action='store_true', help='Header-less mode: omit asm prologue and epilogue') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(VERSION)) parser.add_argument('--parse-only', action='store_true', help='Only parses to check for syntax and semantic errors') parser.add_argument('--append-binary', default=[], action='append', help='Appends binary to tape file (only works with -t or -T)') parser.add_argument('--append-headless-binary', default=[], action='append', help='Appends binary to tape file (only works with -t or -T)') options = parser.parse_args(args=args) # ------------------------------------------------------------ # Setting of internal parameters according to command line # ------------------------------------------------------------ OPTIONS.Debug.value = options.debug OPTIONS.optimization.value = options.optimize OPTIONS.outputFileName.value = options.output_file OPTIONS.StdErrFileName.value = options.stderr OPTIONS.array_base.value = options.array_base OPTIONS.string_base.value = options.string_base OPTIONS.Sinclair.value = options.sinclair OPTIONS.heap_size.value = options.heap_size OPTIONS.memoryCheck.value = options.debug_memory OPTIONS.strictBool.value = options.strict_bool or OPTIONS.Sinclair.value OPTIONS.arrayCheck.value = options.debug_array OPTIONS.emitBackend.value = options.emit_backend OPTIONS.enableBreak.value = options.enable_break OPTIONS.explicit.value = options.explicit OPTIONS.memory_map.value = options.memory_map OPTIONS.strict.value = options.strict OPTIONS.headerless.value = options.headerless OPTIONS.org.value = api.utils.parse_int(options.org) if OPTIONS.org.value is None: parser.error("Invalid --org option '{}'".format(options.org)) if options.defines: for i in options.defines: name, val = tuple(i.split('=', 1)) OPTIONS.__DEFINES.value[name] = val zxbpp.ID_TABLE.define(name, lineno=0) if OPTIONS.Sinclair.value: OPTIONS.array_base.value = 1 OPTIONS.string_base.value = 1 OPTIONS.strictBool.value = True OPTIONS.case_insensitive.value = True if options.ignore_case: OPTIONS.case_insensitive.value = True debug.ENABLED = OPTIONS.Debug.value if int(options.tzx) + int(options.tap) + int(options.asm) + int(options.emit_backend) + \ int(options.parse_only) > 1: parser.error("Options --tap, --tzx, --emit-backend, --parse-only and --asm are mutually exclusive") return 3 if options.basic and not options.tzx and not options.tap: parser.error('Option --BASIC and --autorun requires --tzx or tap format') return 4 if options.append_binary and not options.tzx and not options.tap: parser.error('Option --append-binary needs either --tap or --tzx') return 5 OPTIONS.use_loader.value = options.basic OPTIONS.autorun.value = options.autorun if options.tzx: OPTIONS.output_file_type.value = 'tzx' elif options.tap: OPTIONS.output_file_type.value = 'tap' elif options.asm: OPTIONS.output_file_type.value = 'asm' elif options.emit_backend: OPTIONS.output_file_type.value = 'ic' args = [options.PROGRAM] if not os.path.exists(options.PROGRAM): parser.error("No such file or directory: '%s'" % args[0]) return 2 if OPTIONS.memoryCheck.value: OPTIONS.__DEFINES.value['__MEMORY_CHECK__'] = '' zxbpp.ID_TABLE.define('__MEMORY_CHECK__', lineno=0) if OPTIONS.arrayCheck.value: OPTIONS.__DEFINES.value['__CHECK_ARRAY_BOUNDARY__'] = '' zxbpp.ID_TABLE.define('__CHECK_ARRAY_BOUNDARY__', lineno=0) OPTIONS.include_path.value = options.include_path OPTIONS.inputFileName.value = zxbparser.FILENAME = \ os.path.basename(args[0]) 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_file(OPTIONS.StdErrFileName.value, 'wt', 'utf-8') zxbpp.setMode('basic') zxbpp.main(args) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors input_ = zxbpp.OUTPUT zxbparser.parser.parse(input_, lexer=zxblex.lexer, tracking=True, debug=(OPTIONS.Debug.value > 2)) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors # Optimizations optimizer = api.optimize.OptimizerVisitor() optimizer.visit(zxbparser.ast) # Emits intermediate code translator = arch.zx48k.Translator() translator.visit(zxbparser.ast) if gl.DATA_IS_USED: gl.FUNCTIONS.extend(gl.DATA_FUNCTIONS) # This will fill MEMORY with pending functions func_visitor = arch.zx48k.FunctionTranslator(gl.FUNCTIONS) func_visitor.start() # Emits data lines translator.emit_data_blocks() # Emits default constant strings translator.emit_strings() # Emits jump tables translator.emit_jump_tables() if OPTIONS.emitBackend.value: with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file: for quad in translator.dumpMemory(backend.MEMORY): output_file.write(str(quad) + '\n') backend.MEMORY[:] = [] # Empties memory # This will fill MEMORY with global declared variables translator = arch.zx48k.VarTranslator() translator.visit(zxbparser.data_ast) for quad in translator.dumpMemory(backend.MEMORY): output_file.write(str(quad) + '\n') return 0 # Exit success # Join all lines into a single string and ensures an INTRO at end of file asm_output = backend.emit(backend.MEMORY) asm_output = optimize(asm_output) + '\n' asm_output = asm_output.split('\n') for i in range(len(asm_output)): tmp = backend.ASMS.get(asm_output[i], None) if tmp is not None: asm_output[i] = '\n'.join(tmp) asm_output = '\n'.join(asm_output) # Now filter them against the preprocessor again zxbpp.setMode('asm') zxbpp.OUTPUT = '' zxbpp.filter_(asm_output, args[0]) # Now output the result asm_output = zxbpp.OUTPUT.split('\n') get_inits(asm_output) # Find out remaining inits backend.MEMORY[:] = [] # This will fill MEMORY with global declared variables translator = arch.zx48k.VarTranslator() translator.visit(zxbparser.data_ast) if gl.has_errors: debug.__DEBUG__("exiting due to errors.") return 1 # Exit with errors tmp = [x for x in backend.emit(backend.MEMORY) if x.strip()[0] != '#'] asm_output += tmp asm_output = backend.emit_start() + asm_output asm_output += backend.emit_end(asm_output) if options.asm: # Only output assembler file with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file: output(asm_output, output_file) elif not options.parse_only: fout = StringIO() output(asm_output, fout) asmparse.assemble(fout.getvalue()) fout.close() asmparse.generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type.value, binary_files=options.append_binary, headless_binary_files=options.append_headless_binary) if gl.has_errors: return 5 # Error in assembly if OPTIONS.memory_map.value: with open_file(OPTIONS.memory_map.value, 'wt', 'utf-8') as f: f.write(asmparse.MEMORY.memory_map) return gl.has_errors
[ "def", "main", "(", "args", "=", "None", ")", ":", "api", ".", "config", ".", "init", "(", ")", "zxbpp", ".", "init", "(", ")", "zxbparser", ".", "init", "(", ")", "arch", ".", "zx48k", ".", "backend", ".", "init", "(", ")", "arch", ".", "zx48k", ".", "Translator", ".", "reset", "(", ")", "asmparse", ".", "init", "(", ")", "# ------------------------------------------------------------", "# Command line parsing", "# ------------------------------------------------------------", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'zxb'", ")", "parser", ".", "add_argument", "(", "'PROGRAM'", ",", "type", "=", "str", ",", "help", "=", "'BASIC program file'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--debug'", ",", "dest", "=", "'debug'", ",", "default", "=", "OPTIONS", ".", "Debug", ".", "value", ",", "action", "=", "'count'", ",", "help", "=", "'Enable verbosity/debugging output. Additional -d increase verbosity/debug level'", ")", "parser", ".", "add_argument", "(", "'-O'", ",", "'--optimize'", ",", "type", "=", "int", ",", "default", "=", "OPTIONS", ".", "optimization", ".", "value", ",", "help", "=", "'Sets optimization level. '", "'0 = None (default level is {0})'", ".", "format", "(", "OPTIONS", ".", "optimization", ".", "value", ")", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--output'", ",", "type", "=", "str", ",", "dest", "=", "'output_file'", ",", "default", "=", "None", ",", "help", "=", "'Sets output file. Default is input filename with .bin extension'", ")", "parser", ".", "add_argument", "(", "'-T'", ",", "'--tzx'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Sets output format to tzx (default is .bin)\"", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--tap'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Sets output format to tap (default is .bin)\"", ")", "parser", ".", "add_argument", "(", "'-B'", ",", "'--BASIC'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'basic'", ",", "help", "=", "\"Creates a BASIC loader which loads the rest of the CODE. Requires -T ot -t\"", ")", "parser", ".", "add_argument", "(", "'-a'", ",", "'--autorun'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Sets the program to be run once loaded\"", ")", "parser", ".", "add_argument", "(", "'-A'", ",", "'--asm'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Sets output format to asm\"", ")", "parser", ".", "add_argument", "(", "'-S'", ",", "'--org'", ",", "type", "=", "str", ",", "default", "=", "str", "(", "OPTIONS", ".", "org", ".", "value", ")", ",", "help", "=", "\"Start of machine code. By default %i\"", "%", "OPTIONS", ".", "org", ".", "value", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--errmsg'", ",", "type", "=", "str", ",", "dest", "=", "'stderr'", ",", "default", "=", "OPTIONS", ".", "StdErrFileName", ".", "value", ",", "help", "=", "'Error messages file (standard error console by default)'", ")", "parser", ".", "add_argument", "(", "'--array-base'", ",", "type", "=", "int", ",", "default", "=", "OPTIONS", ".", "array_base", ".", "value", ",", "help", "=", "'Default lower index for arrays ({0} by default)'", ".", "format", "(", "OPTIONS", ".", "array_base", ".", "value", ")", ")", "parser", ".", "add_argument", "(", "'--string-base'", ",", "type", "=", "int", ",", "default", "=", "OPTIONS", ".", "string_base", ".", "value", ",", "help", "=", "'Default lower index for strings ({0} by default)'", ".", "format", "(", "OPTIONS", ".", "array_base", ".", "value", ")", ")", "parser", ".", "add_argument", "(", "'-Z'", ",", "'--sinclair'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable by default some more original ZX Spectrum Sinclair BASIC features: ATTR, SCREEN$, '", "'POINT'", ")", "parser", ".", "add_argument", "(", "'-H'", ",", "'--heap-size'", ",", "type", "=", "int", ",", "default", "=", "OPTIONS", ".", "heap_size", ".", "value", ",", "help", "=", "'Sets heap size in bytes (default {0} bytes)'", ".", "format", "(", "OPTIONS", ".", "heap_size", ".", "value", ")", ")", "parser", ".", "add_argument", "(", "'--debug-memory'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enables out-of-memory debug'", ")", "parser", ".", "add_argument", "(", "'--debug-array'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enables array boundary checking'", ")", "parser", ".", "add_argument", "(", "'--strict-bool'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enforce boolean values to be 0 or 1'", ")", "parser", ".", "add_argument", "(", "'--enable-break'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enables program execution BREAK detection'", ")", "parser", ".", "add_argument", "(", "'-E'", ",", "'--emit-backend'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Emits backend code instead of ASM or binary'", ")", "parser", ".", "add_argument", "(", "'--explicit'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Requires all variables and functions to be declared before used'", ")", "parser", ".", "add_argument", "(", "'-D'", ",", "'--define'", ",", "type", "=", "str", ",", "dest", "=", "'defines'", ",", "action", "=", "'append'", ",", "help", "=", "'Defines de given macro. Eg. -D MYDEBUG or -D NAME=Value'", ")", "parser", ".", "add_argument", "(", "'-M'", ",", "'--mmap'", ",", "type", "=", "str", ",", "dest", "=", "'memory_map'", ",", "default", "=", "None", ",", "help", "=", "'Generate label memory map'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--ignore-case'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Ignore case. Makes variable names are case insensitive'", ")", "parser", ".", "add_argument", "(", "'-I'", ",", "'--include-path'", ",", "type", "=", "str", ",", "default", "=", "''", ",", "help", "=", "'Add colon separated list of directories to add to include path. e.g. -I dir1:dir2'", ")", "parser", ".", "add_argument", "(", "'--strict'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enables strict mode. Force explicit type declaration'", ")", "parser", ".", "add_argument", "(", "'--headerless'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Header-less mode: omit asm prologue and epilogue'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s {0}'", ".", "format", "(", "VERSION", ")", ")", "parser", ".", "add_argument", "(", "'--parse-only'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Only parses to check for syntax and semantic errors'", ")", "parser", ".", "add_argument", "(", "'--append-binary'", ",", "default", "=", "[", "]", ",", "action", "=", "'append'", ",", "help", "=", "'Appends binary to tape file (only works with -t or -T)'", ")", "parser", ".", "add_argument", "(", "'--append-headless-binary'", ",", "default", "=", "[", "]", ",", "action", "=", "'append'", ",", "help", "=", "'Appends binary to tape file (only works with -t or -T)'", ")", "options", "=", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "# ------------------------------------------------------------", "# Setting of internal parameters according to command line", "# ------------------------------------------------------------", "OPTIONS", ".", "Debug", ".", "value", "=", "options", ".", "debug", "OPTIONS", ".", "optimization", ".", "value", "=", "options", ".", "optimize", "OPTIONS", ".", "outputFileName", ".", "value", "=", "options", ".", "output_file", "OPTIONS", ".", "StdErrFileName", ".", "value", "=", "options", ".", "stderr", "OPTIONS", ".", "array_base", ".", "value", "=", "options", ".", "array_base", "OPTIONS", ".", "string_base", ".", "value", "=", "options", ".", "string_base", "OPTIONS", ".", "Sinclair", ".", "value", "=", "options", ".", "sinclair", "OPTIONS", ".", "heap_size", ".", "value", "=", "options", ".", "heap_size", "OPTIONS", ".", "memoryCheck", ".", "value", "=", "options", ".", "debug_memory", "OPTIONS", ".", "strictBool", ".", "value", "=", "options", ".", "strict_bool", "or", "OPTIONS", ".", "Sinclair", ".", "value", "OPTIONS", ".", "arrayCheck", ".", "value", "=", "options", ".", "debug_array", "OPTIONS", ".", "emitBackend", ".", "value", "=", "options", ".", "emit_backend", "OPTIONS", ".", "enableBreak", ".", "value", "=", "options", ".", "enable_break", "OPTIONS", ".", "explicit", ".", "value", "=", "options", ".", "explicit", "OPTIONS", ".", "memory_map", ".", "value", "=", "options", ".", "memory_map", "OPTIONS", ".", "strict", ".", "value", "=", "options", ".", "strict", "OPTIONS", ".", "headerless", ".", "value", "=", "options", ".", "headerless", "OPTIONS", ".", "org", ".", "value", "=", "api", ".", "utils", ".", "parse_int", "(", "options", ".", "org", ")", "if", "OPTIONS", ".", "org", ".", "value", "is", "None", ":", "parser", ".", "error", "(", "\"Invalid --org option '{}'\"", ".", "format", "(", "options", ".", "org", ")", ")", "if", "options", ".", "defines", ":", "for", "i", "in", "options", ".", "defines", ":", "name", ",", "val", "=", "tuple", "(", "i", ".", "split", "(", "'='", ",", "1", ")", ")", "OPTIONS", ".", "__DEFINES", ".", "value", "[", "name", "]", "=", "val", "zxbpp", ".", "ID_TABLE", ".", "define", "(", "name", ",", "lineno", "=", "0", ")", "if", "OPTIONS", ".", "Sinclair", ".", "value", ":", "OPTIONS", ".", "array_base", ".", "value", "=", "1", "OPTIONS", ".", "string_base", ".", "value", "=", "1", "OPTIONS", ".", "strictBool", ".", "value", "=", "True", "OPTIONS", ".", "case_insensitive", ".", "value", "=", "True", "if", "options", ".", "ignore_case", ":", "OPTIONS", ".", "case_insensitive", ".", "value", "=", "True", "debug", ".", "ENABLED", "=", "OPTIONS", ".", "Debug", ".", "value", "if", "int", "(", "options", ".", "tzx", ")", "+", "int", "(", "options", ".", "tap", ")", "+", "int", "(", "options", ".", "asm", ")", "+", "int", "(", "options", ".", "emit_backend", ")", "+", "int", "(", "options", ".", "parse_only", ")", ">", "1", ":", "parser", ".", "error", "(", "\"Options --tap, --tzx, --emit-backend, --parse-only and --asm are mutually exclusive\"", ")", "return", "3", "if", "options", ".", "basic", "and", "not", "options", ".", "tzx", "and", "not", "options", ".", "tap", ":", "parser", ".", "error", "(", "'Option --BASIC and --autorun requires --tzx or tap format'", ")", "return", "4", "if", "options", ".", "append_binary", "and", "not", "options", ".", "tzx", "and", "not", "options", ".", "tap", ":", "parser", ".", "error", "(", "'Option --append-binary needs either --tap or --tzx'", ")", "return", "5", "OPTIONS", ".", "use_loader", ".", "value", "=", "options", ".", "basic", "OPTIONS", ".", "autorun", ".", "value", "=", "options", ".", "autorun", "if", "options", ".", "tzx", ":", "OPTIONS", ".", "output_file_type", ".", "value", "=", "'tzx'", "elif", "options", ".", "tap", ":", "OPTIONS", ".", "output_file_type", ".", "value", "=", "'tap'", "elif", "options", ".", "asm", ":", "OPTIONS", ".", "output_file_type", ".", "value", "=", "'asm'", "elif", "options", ".", "emit_backend", ":", "OPTIONS", ".", "output_file_type", ".", "value", "=", "'ic'", "args", "=", "[", "options", ".", "PROGRAM", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "options", ".", "PROGRAM", ")", ":", "parser", ".", "error", "(", "\"No such file or directory: '%s'\"", "%", "args", "[", "0", "]", ")", "return", "2", "if", "OPTIONS", ".", "memoryCheck", ".", "value", ":", "OPTIONS", ".", "__DEFINES", ".", "value", "[", "'__MEMORY_CHECK__'", "]", "=", "''", "zxbpp", ".", "ID_TABLE", ".", "define", "(", "'__MEMORY_CHECK__'", ",", "lineno", "=", "0", ")", "if", "OPTIONS", ".", "arrayCheck", ".", "value", ":", "OPTIONS", ".", "__DEFINES", ".", "value", "[", "'__CHECK_ARRAY_BOUNDARY__'", "]", "=", "''", "zxbpp", ".", "ID_TABLE", ".", "define", "(", "'__CHECK_ARRAY_BOUNDARY__'", ",", "lineno", "=", "0", ")", "OPTIONS", ".", "include_path", ".", "value", "=", "options", ".", "include_path", "OPTIONS", ".", "inputFileName", ".", "value", "=", "zxbparser", ".", "FILENAME", "=", "os", ".", "path", ".", "basename", "(", "args", "[", "0", "]", ")", "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_file", "(", "OPTIONS", ".", "StdErrFileName", ".", "value", ",", "'wt'", ",", "'utf-8'", ")", "zxbpp", ".", "setMode", "(", "'basic'", ")", "zxbpp", ".", "main", "(", "args", ")", "if", "gl", ".", "has_errors", ":", "debug", ".", "__DEBUG__", "(", "\"exiting due to errors.\"", ")", "return", "1", "# Exit with errors", "input_", "=", "zxbpp", ".", "OUTPUT", "zxbparser", ".", "parser", ".", "parse", "(", "input_", ",", "lexer", "=", "zxblex", ".", "lexer", ",", "tracking", "=", "True", ",", "debug", "=", "(", "OPTIONS", ".", "Debug", ".", "value", ">", "2", ")", ")", "if", "gl", ".", "has_errors", ":", "debug", ".", "__DEBUG__", "(", "\"exiting due to errors.\"", ")", "return", "1", "# Exit with errors", "# Optimizations", "optimizer", "=", "api", ".", "optimize", ".", "OptimizerVisitor", "(", ")", "optimizer", ".", "visit", "(", "zxbparser", ".", "ast", ")", "# Emits intermediate code", "translator", "=", "arch", ".", "zx48k", ".", "Translator", "(", ")", "translator", ".", "visit", "(", "zxbparser", ".", "ast", ")", "if", "gl", ".", "DATA_IS_USED", ":", "gl", ".", "FUNCTIONS", ".", "extend", "(", "gl", ".", "DATA_FUNCTIONS", ")", "# This will fill MEMORY with pending functions", "func_visitor", "=", "arch", ".", "zx48k", ".", "FunctionTranslator", "(", "gl", ".", "FUNCTIONS", ")", "func_visitor", ".", "start", "(", ")", "# Emits data lines", "translator", ".", "emit_data_blocks", "(", ")", "# Emits default constant strings", "translator", ".", "emit_strings", "(", ")", "# Emits jump tables", "translator", ".", "emit_jump_tables", "(", ")", "if", "OPTIONS", ".", "emitBackend", ".", "value", ":", "with", "open_file", "(", "OPTIONS", ".", "outputFileName", ".", "value", ",", "'wt'", ",", "'utf-8'", ")", "as", "output_file", ":", "for", "quad", "in", "translator", ".", "dumpMemory", "(", "backend", ".", "MEMORY", ")", ":", "output_file", ".", "write", "(", "str", "(", "quad", ")", "+", "'\\n'", ")", "backend", ".", "MEMORY", "[", ":", "]", "=", "[", "]", "# Empties memory", "# This will fill MEMORY with global declared variables", "translator", "=", "arch", ".", "zx48k", ".", "VarTranslator", "(", ")", "translator", ".", "visit", "(", "zxbparser", ".", "data_ast", ")", "for", "quad", "in", "translator", ".", "dumpMemory", "(", "backend", ".", "MEMORY", ")", ":", "output_file", ".", "write", "(", "str", "(", "quad", ")", "+", "'\\n'", ")", "return", "0", "# Exit success", "# Join all lines into a single string and ensures an INTRO at end of file", "asm_output", "=", "backend", ".", "emit", "(", "backend", ".", "MEMORY", ")", "asm_output", "=", "optimize", "(", "asm_output", ")", "+", "'\\n'", "asm_output", "=", "asm_output", ".", "split", "(", "'\\n'", ")", "for", "i", "in", "range", "(", "len", "(", "asm_output", ")", ")", ":", "tmp", "=", "backend", ".", "ASMS", ".", "get", "(", "asm_output", "[", "i", "]", ",", "None", ")", "if", "tmp", "is", "not", "None", ":", "asm_output", "[", "i", "]", "=", "'\\n'", ".", "join", "(", "tmp", ")", "asm_output", "=", "'\\n'", ".", "join", "(", "asm_output", ")", "# Now filter them against the preprocessor again", "zxbpp", ".", "setMode", "(", "'asm'", ")", "zxbpp", ".", "OUTPUT", "=", "''", "zxbpp", ".", "filter_", "(", "asm_output", ",", "args", "[", "0", "]", ")", "# Now output the result", "asm_output", "=", "zxbpp", ".", "OUTPUT", ".", "split", "(", "'\\n'", ")", "get_inits", "(", "asm_output", ")", "# Find out remaining inits", "backend", ".", "MEMORY", "[", ":", "]", "=", "[", "]", "# This will fill MEMORY with global declared variables", "translator", "=", "arch", ".", "zx48k", ".", "VarTranslator", "(", ")", "translator", ".", "visit", "(", "zxbparser", ".", "data_ast", ")", "if", "gl", ".", "has_errors", ":", "debug", ".", "__DEBUG__", "(", "\"exiting due to errors.\"", ")", "return", "1", "# Exit with errors", "tmp", "=", "[", "x", "for", "x", "in", "backend", ".", "emit", "(", "backend", ".", "MEMORY", ")", "if", "x", ".", "strip", "(", ")", "[", "0", "]", "!=", "'#'", "]", "asm_output", "+=", "tmp", "asm_output", "=", "backend", ".", "emit_start", "(", ")", "+", "asm_output", "asm_output", "+=", "backend", ".", "emit_end", "(", "asm_output", ")", "if", "options", ".", "asm", ":", "# Only output assembler file", "with", "open_file", "(", "OPTIONS", ".", "outputFileName", ".", "value", ",", "'wt'", ",", "'utf-8'", ")", "as", "output_file", ":", "output", "(", "asm_output", ",", "output_file", ")", "elif", "not", "options", ".", "parse_only", ":", "fout", "=", "StringIO", "(", ")", "output", "(", "asm_output", ",", "fout", ")", "asmparse", ".", "assemble", "(", "fout", ".", "getvalue", "(", ")", ")", "fout", ".", "close", "(", ")", "asmparse", ".", "generate_binary", "(", "OPTIONS", ".", "outputFileName", ".", "value", ",", "OPTIONS", ".", "output_file_type", ".", "value", ",", "binary_files", "=", "options", ".", "append_binary", ",", "headless_binary_files", "=", "options", ".", "append_headless_binary", ")", "if", "gl", ".", "has_errors", ":", "return", "5", "# Error in assembly", "if", "OPTIONS", ".", "memory_map", ".", "value", ":", "with", "open_file", "(", "OPTIONS", ".", "memory_map", ".", "value", ",", "'wt'", ",", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "asmparse", ".", "MEMORY", ".", "memory_map", ")", "return", "gl", ".", "has_errors" ]
Entry point when executed from command line. You can use zxb.py as a module with import, and this function won't be executed.
[ "Entry", "point", "when", "executed", "from", "command", "line", ".", "You", "can", "use", "zxb", ".", "py", "as", "a", "module", "with", "import", "and", "this", "function", "won", "t", "be", "executed", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxb.py#L74-L351
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_16bit_oper
def _16bit_oper(op1, op2=None, reversed=False): ''' Returns pop sequence for 16 bits operands 1st operand in HL, 2nd operand in DE For subtraction, division, etc. you can swap operators extraction order by setting reversed to True ''' output = [] if op1 is not None: op1 = str(op1) # always to str if op2 is not None: op2 = str(op2) # always to str if op2 is not None and reversed: op1, op2 = op2, op1 op = op1 indirect = (op[0] == '*') if indirect: op = op[1:] immediate = (op[0] == '#') if immediate: op = op[1:] if is_int(op): op = int(op) if indirect: output.append('ld hl, (%i)' % op) else: output.append('ld hl, %i' % int16(op)) else: if immediate: if indirect: output.append('ld hl, (%s)' % op) else: output.append('ld hl, %s' % op) else: if op[0] == '_': output.append('ld hl, (%s)' % op) else: output.append('pop hl') if indirect: output.append('ld a, (hl)') output.append('inc hl') output.append('ld h, (hl)') output.append('ld l, a') if op2 is None: return output if not reversed: tmp = output output = [] op = op2 indirect = (op[0] == '*') if indirect: op = op[1:] immediate = (op[0] == '#') if immediate: op = op[1:] if is_int(op): op = int(op) if indirect: output.append('ld de, (%i)' % op) else: output.append('ld de, %i' % int16(op)) else: if immediate: output.append('ld de, %s' % op) else: if op[0] == '_': output.append('ld de, (%s)' % op) else: output.append('pop de') if indirect: output.append('call __LOAD_DE_DE') # DE = (DE) REQUIRES.add('lddede.asm') if not reversed: output.extend(tmp) return output
python
def _16bit_oper(op1, op2=None, reversed=False): ''' Returns pop sequence for 16 bits operands 1st operand in HL, 2nd operand in DE For subtraction, division, etc. you can swap operators extraction order by setting reversed to True ''' output = [] if op1 is not None: op1 = str(op1) # always to str if op2 is not None: op2 = str(op2) # always to str if op2 is not None and reversed: op1, op2 = op2, op1 op = op1 indirect = (op[0] == '*') if indirect: op = op[1:] immediate = (op[0] == '#') if immediate: op = op[1:] if is_int(op): op = int(op) if indirect: output.append('ld hl, (%i)' % op) else: output.append('ld hl, %i' % int16(op)) else: if immediate: if indirect: output.append('ld hl, (%s)' % op) else: output.append('ld hl, %s' % op) else: if op[0] == '_': output.append('ld hl, (%s)' % op) else: output.append('pop hl') if indirect: output.append('ld a, (hl)') output.append('inc hl') output.append('ld h, (hl)') output.append('ld l, a') if op2 is None: return output if not reversed: tmp = output output = [] op = op2 indirect = (op[0] == '*') if indirect: op = op[1:] immediate = (op[0] == '#') if immediate: op = op[1:] if is_int(op): op = int(op) if indirect: output.append('ld de, (%i)' % op) else: output.append('ld de, %i' % int16(op)) else: if immediate: output.append('ld de, %s' % op) else: if op[0] == '_': output.append('ld de, (%s)' % op) else: output.append('pop de') if indirect: output.append('call __LOAD_DE_DE') # DE = (DE) REQUIRES.add('lddede.asm') if not reversed: output.extend(tmp) return output
[ "def", "_16bit_oper", "(", "op1", ",", "op2", "=", "None", ",", "reversed", "=", "False", ")", ":", "output", "=", "[", "]", "if", "op1", "is", "not", "None", ":", "op1", "=", "str", "(", "op1", ")", "# always to str", "if", "op2", "is", "not", "None", ":", "op2", "=", "str", "(", "op2", ")", "# always to str", "if", "op2", "is", "not", "None", "and", "reversed", ":", "op1", ",", "op2", "=", "op2", ",", "op1", "op", "=", "op1", "indirect", "=", "(", "op", "[", "0", "]", "==", "'*'", ")", "if", "indirect", ":", "op", "=", "op", "[", "1", ":", "]", "immediate", "=", "(", "op", "[", "0", "]", "==", "'#'", ")", "if", "immediate", ":", "op", "=", "op", "[", "1", ":", "]", "if", "is_int", "(", "op", ")", ":", "op", "=", "int", "(", "op", ")", "if", "indirect", ":", "output", ".", "append", "(", "'ld hl, (%i)'", "%", "op", ")", "else", ":", "output", ".", "append", "(", "'ld hl, %i'", "%", "int16", "(", "op", ")", ")", "else", ":", "if", "immediate", ":", "if", "indirect", ":", "output", ".", "append", "(", "'ld hl, (%s)'", "%", "op", ")", "else", ":", "output", ".", "append", "(", "'ld hl, %s'", "%", "op", ")", "else", ":", "if", "op", "[", "0", "]", "==", "'_'", ":", "output", ".", "append", "(", "'ld hl, (%s)'", "%", "op", ")", "else", ":", "output", ".", "append", "(", "'pop hl'", ")", "if", "indirect", ":", "output", ".", "append", "(", "'ld a, (hl)'", ")", "output", ".", "append", "(", "'inc hl'", ")", "output", ".", "append", "(", "'ld h, (hl)'", ")", "output", ".", "append", "(", "'ld l, a'", ")", "if", "op2", "is", "None", ":", "return", "output", "if", "not", "reversed", ":", "tmp", "=", "output", "output", "=", "[", "]", "op", "=", "op2", "indirect", "=", "(", "op", "[", "0", "]", "==", "'*'", ")", "if", "indirect", ":", "op", "=", "op", "[", "1", ":", "]", "immediate", "=", "(", "op", "[", "0", "]", "==", "'#'", ")", "if", "immediate", ":", "op", "=", "op", "[", "1", ":", "]", "if", "is_int", "(", "op", ")", ":", "op", "=", "int", "(", "op", ")", "if", "indirect", ":", "output", ".", "append", "(", "'ld de, (%i)'", "%", "op", ")", "else", ":", "output", ".", "append", "(", "'ld de, %i'", "%", "int16", "(", "op", ")", ")", "else", ":", "if", "immediate", ":", "output", ".", "append", "(", "'ld de, %s'", "%", "op", ")", "else", ":", "if", "op", "[", "0", "]", "==", "'_'", ":", "output", ".", "append", "(", "'ld de, (%s)'", "%", "op", ")", "else", ":", "output", ".", "append", "(", "'pop de'", ")", "if", "indirect", ":", "output", ".", "append", "(", "'call __LOAD_DE_DE'", ")", "# DE = (DE)", "REQUIRES", ".", "add", "(", "'lddede.asm'", ")", "if", "not", "reversed", ":", "output", ".", "extend", "(", "tmp", ")", "return", "output" ]
Returns pop sequence for 16 bits operands 1st operand in HL, 2nd operand in DE For subtraction, division, etc. you can swap operators extraction order by setting reversed to True
[ "Returns", "pop", "sequence", "for", "16", "bits", "operands", "1st", "operand", "in", "HL", "2nd", "operand", "in", "DE" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L26-L117
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_add16
def _add16(ins): ''' Pops last 2 bytes from the stack and adds them. Then push the result onto the stack. Optimizations: * If any of the operands is ZERO, then do NOTHING: A + 0 = 0 + A = A * If any of the operands is < 4, then INC is used * If any of the operands is > (65531) (-4), then DEC is used ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) op2 = int16(op2) output = _16bit_oper(op1) if op2 == 0: output.append('push hl') return output # ADD HL, 0 => NOTHING if op2 < 4: output.extend(['inc hl'] * op2) # ADD HL, 2 ==> inc hl; inc hl output.append('push hl') return output if op2 > 65531: # (between -4 and 0) output.extend(['dec hl'] * (0x10000 - op2)) output.append('push hl') return output output.append('ld de, %i' % op2) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('add hl, de') output.append('push hl') return output
python
def _add16(ins): ''' Pops last 2 bytes from the stack and adds them. Then push the result onto the stack. Optimizations: * If any of the operands is ZERO, then do NOTHING: A + 0 = 0 + A = A * If any of the operands is < 4, then INC is used * If any of the operands is > (65531) (-4), then DEC is used ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) op2 = int16(op2) output = _16bit_oper(op1) if op2 == 0: output.append('push hl') return output # ADD HL, 0 => NOTHING if op2 < 4: output.extend(['inc hl'] * op2) # ADD HL, 2 ==> inc hl; inc hl output.append('push hl') return output if op2 > 65531: # (between -4 and 0) output.extend(['dec hl'] * (0x10000 - op2)) output.append('push hl') return output output.append('ld de, %i' % op2) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('add hl, de') output.append('push hl') return output
[ "def", "_add16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", "is", "not", "None", ":", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "op2", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "# ADD HL, 0 => NOTHING", "if", "op2", "<", "4", ":", "output", ".", "extend", "(", "[", "'inc hl'", "]", "*", "op2", ")", "# ADD HL, 2 ==> inc hl; inc hl", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", ">", "65531", ":", "# (between -4 and 0)", "output", ".", "extend", "(", "[", "'dec hl'", "]", "*", "(", "0x10000", "-", "op2", ")", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op2", ")", "output", ".", "append", "(", "'add hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# stack optimization", "op1", ",", "op2", "=", "op2", ",", "op1", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'add hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Pops last 2 bytes from the stack and adds them. Then push the result onto the stack. Optimizations: * If any of the operands is ZERO, then do NOTHING: A + 0 = 0 + A = A * If any of the operands is < 4, then INC is used * If any of the operands is > (65531) (-4), then DEC is used
[ "Pops", "last", "2", "bytes", "from", "the", "stack", "and", "adds", "them", ".", "Then", "push", "the", "result", "onto", "the", "stack", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L124-L170
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_sub16
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used ''' op1, op2 = tuple(ins.quad[2:4]) if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op == 0: output.append('push hl') return output if op < 4: output.extend(['dec hl'] * op) output.append('push hl') return output if op > 65531: output.extend(['inc hl'] * (0x10000 - op)) output.append('push hl') return output output.append('ld de, -%i' % op) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('or a') output.append('sbc hl, de') output.append('push hl') return output
python
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used ''' op1, op2 = tuple(ins.quad[2:4]) if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op == 0: output.append('push hl') return output if op < 4: output.extend(['dec hl'] * op) output.append('push hl') return output if op > 65531: output.extend(['inc hl'] * (0x10000 - op)) output.append('push hl') return output output.append('ld de, -%i' % op) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('or a') output.append('sbc hl, de') output.append('push hl') return output
[ "def", "_sub16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "4", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op", "==", "0", ":", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "<", "4", ":", "output", ".", "extend", "(", "[", "'dec hl'", "]", "*", "op", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", ">", "65531", ":", "output", ".", "extend", "(", "[", "'inc hl'", "]", "*", "(", "0x10000", "-", "op", ")", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, -%i'", "%", "op", ")", "output", ".", "append", "(", "'add hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# Optimization when 2nd operand is an id", "rev", "=", "True", "op1", ",", "op2", "=", "op2", ",", "op1", "else", ":", "rev", "=", "False", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ",", "rev", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used
[ "Pops", "last", "2", "words", "from", "the", "stack", "and", "subtract", "them", ".", "Then", "push", "the", "result", "onto", "the", "stack", ".", "Top", "of", "the", "stack", "is", "subtracted", "Top", "-", "1" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L173-L223
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_mul16
def _mul16(ins): ''' Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: # If any of the operands is constant op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op2 == 1: # A * 1 = 1 * A == A => Do nothing output.append('push hl') return output if op2 == 0xFFFF: # This is the same as (-1) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output if is_2n(op2) and log2(op2) < 4: output.extend(['add hl, hl'] * int(log2(op2))) output.append('push hl') return output output.append('ld de, %i' % op2) else: if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('call __MUL16_FAST') # Inmmediate output.append('push hl') REQUIRES.add('mul16.asm') return output
python
def _mul16(ins): ''' Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: # If any of the operands is constant op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op2 == 1: # A * 1 = 1 * A == A => Do nothing output.append('push hl') return output if op2 == 0xFFFF: # This is the same as (-1) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output if is_2n(op2) and log2(op2) < 4: output.extend(['add hl, hl'] * int(log2(op2))) output.append('push hl') return output output.append('ld de, %i' % op2) else: if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('call __MUL16_FAST') # Inmmediate output.append('push hl') REQUIRES.add('mul16.asm') return output
[ "def", "_mul16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", "is", "not", "None", ":", "# If any of the operands is constant", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "# put the constant one the 2nd", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "# A * 0 = 0 * A = 0", "if", "op1", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "==", "1", ":", "# A * 1 = 1 * A == A => Do nothing", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "==", "0xFFFF", ":", "# This is the same as (-1)", "output", ".", "append", "(", "'call __NEGHL'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'neg16.asm'", ")", "return", "output", "if", "is_2n", "(", "op2", ")", "and", "log2", "(", "op2", ")", "<", "4", ":", "output", ".", "extend", "(", "[", "'add hl, hl'", "]", "*", "int", "(", "log2", "(", "op2", ")", ")", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op2", ")", "else", ":", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# stack optimization", "op1", ",", "op2", "=", "op2", ",", "op1", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'call __MUL16_FAST'", ")", "# Inmmediate", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'mul16.asm'", ")", "return", "output" ]
Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n
[ "Multiplies", "tow", "last", "16bit", "values", "on", "top", "of", "the", "stack", "and", "and", "returns", "the", "value", "on", "top", "of", "the", "stack" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L226-L276
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_divu16
def _divu16(ins): ''' Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op1) and int(op1) == 0: # 0 / A = 0 if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack else: output = _16bit_oper(op2) # Normalize stack output.append('ld hl, 0') output.append('push hl') return output if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op == 1: output.append('push hl') return output if op == 2: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld de, %i' % op) else: if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('call __DIVU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
def _divu16(ins): ''' Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op1) and int(op1) == 0: # 0 / A = 0 if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack else: output = _16bit_oper(op2) # Normalize stack output.append('ld hl, 0') output.append('push hl') return output if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op == 1: output.append('push hl') return output if op == 2: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld de, %i' % op) else: if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('call __DIVU16') output.append('push hl') REQUIRES.add('div16.asm') return output
[ "def", "_divu16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op1", ")", "and", "int", "(", "op1", ")", "==", "0", ":", "# 0 / A = 0", "if", "op2", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "else", ":", "output", "=", "_16bit_oper", "(", "op2", ")", "# Normalize stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "# A * 0 = 0 * A = 0", "if", "op1", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "==", "1", ":", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "==", "2", ":", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op", ")", "else", ":", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# Optimization when 2nd operand is an id", "rev", "=", "True", "op1", ",", "op2", "=", "op2", ",", "op1", "else", ":", "rev", "=", "False", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ",", "rev", ")", "output", ".", "append", "(", "'call __DIVU16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'div16.asm'", ")", "return", "output" ]
Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical
[ "Divides", "2", "16bit", "unsigned", "integers", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L279-L333
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_modu16
def _modu16(ins): ''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1) ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op2 = int16(op2) output = _16bit_oper(op1) if op2 == 1: if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if is_2n(op2): k = op2 - 1 if op2 > 255: # only affects H output.append('ld a, h') output.append('and %i' % (k >> 8)) output.append('ld h, a') else: output.append('ld h, 0') # High part goes 0 output.append('ld a, l') output.append('and %i' % (k % 0xFF)) output.append('ld l, a') output.append('push hl') return output output.append('ld de, %i' % op2) else: output = _16bit_oper(op1, op2) output.append('call __MODU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
def _modu16(ins): ''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1) ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op2 = int16(op2) output = _16bit_oper(op1) if op2 == 1: if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if is_2n(op2): k = op2 - 1 if op2 > 255: # only affects H output.append('ld a, h') output.append('and %i' % (k >> 8)) output.append('ld h, a') else: output.append('ld h, 0') # High part goes 0 output.append('ld a, l') output.append('and %i' % (k % 0xFF)) output.append('ld l, a') output.append('push hl') return output output.append('ld de, %i' % op2) else: output = _16bit_oper(op1, op2) output.append('call __MODU16') output.append('push hl') REQUIRES.add('div16.asm') return output
[ "def", "_modu16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op2", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "1", ":", "if", "op2", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "is_2n", "(", "op2", ")", ":", "k", "=", "op2", "-", "1", "if", "op2", ">", "255", ":", "# only affects H", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'and %i'", "%", "(", "k", ">>", "8", ")", ")", "output", ".", "append", "(", "'ld h, a'", ")", "else", ":", "output", ".", "append", "(", "'ld h, 0'", ")", "# High part goes 0", "output", ".", "append", "(", "'ld a, l'", ")", "output", ".", "append", "(", "'and %i'", "%", "(", "k", "%", "0xFF", ")", ")", "output", ".", "append", "(", "'ld l, a'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op2", ")", "else", ":", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'call __MODU16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'div16.asm'", ")", "return", "output" ]
Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1)
[ "Reminder", "of", "div", ".", "2", "16bit", "unsigned", "integers", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L395-L438
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_ltu16
def _ltu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') output.append('sbc hl, de') output.append('sbc a, a') output.append('push af') return output
python
def _ltu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') output.append('sbc hl, de') output.append('sbc a, a') output.append('push af') return output
[ "def", "_ltu16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "<", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L487-L499
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_lti16
def _lti16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __LTI16') output.append('push af') REQUIRES.add('lti16.asm') return output
python
def _lti16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __LTI16') output.append('push af') REQUIRES.add('lti16.asm') return output
[ "def", "_lti16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'call __LTI16'", ")", "output", ".", "append", "(", "'push af'", ")", "REQUIRES", ".", "add", "(", "'lti16.asm'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand < 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "<", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L502-L513
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_gtu16
def _gtu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('or a') output.append('sbc hl, de') output.append('sbc a, a') output.append('push af') return output
python
def _gtu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('or a') output.append('sbc hl, de') output.append('sbc a, a') output.append('push af') return output
[ "def", "_gtu16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ",", "reversed", "=", "True", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", ">", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L516-L528
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_gti16
def _gti16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('call __LTI16') output.append('push af') REQUIRES.add('lti16.asm') return output
python
def _gti16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('call __LTI16') output.append('push af') REQUIRES.add('lti16.asm') return output
[ "def", "_gti16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ",", "reversed", "=", "True", ")", "output", ".", "append", "(", "'call __LTI16'", ")", "output", ".", "append", "(", "'push af'", ")", "REQUIRES", ".", "add", "(", "'lti16.asm'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", ">", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L531-L542
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_leu16
def _leu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('or a') output.append('sbc hl, de') # Carry if A > B output.append('ccf') # Negates the result => Carry if A <= B output.append('sbc a, a') output.append('push af') return output
python
def _leu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True) output.append('or a') output.append('sbc hl, de') # Carry if A > B output.append('ccf') # Negates the result => Carry if A <= B output.append('sbc a, a') output.append('push af') return output
[ "def", "_leu16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ",", "reversed", "=", "True", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "# Carry if A > B", "output", ".", "append", "(", "'ccf'", ")", "# Negates the result => Carry if A <= B", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "<", "=", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L545-L558
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_lei16
def _lei16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __LEI16') output.append('push af') REQUIRES.add('lei16.asm') return output
python
def _lei16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __LEI16') output.append('push af') REQUIRES.add('lei16.asm') return output
[ "def", "_lei16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'call __LEI16'", ")", "output", ".", "append", "(", "'push af'", ")", "REQUIRES", ".", "add", "(", "'lei16.asm'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand <= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit signed version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "<", "=", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L561-L572
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_geu16
def _geu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand >= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') output.append('sbc hl, de') output.append('ccf') output.append('sbc a, a') output.append('push af') return output
python
def _geu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand >= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') output.append('sbc hl, de') output.append('ccf') output.append('sbc a, a') output.append('push af') return output
[ "def", "_geu16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'ccf'", ")", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand >= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", ">", "=", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L575-L588
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_eq16
def _eq16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand == 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __EQ16') output.append('push af') REQUIRES.add('eq16.asm') return output
python
def _eq16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand == 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('call __EQ16') output.append('push af') REQUIRES.add('eq16.asm') return output
[ "def", "_eq16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'call __EQ16'", ")", "output", ".", "append", "(", "'push af'", ")", "REQUIRES", ".", "add", "(", "'eq16.asm'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand == 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "==", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L605-L617
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_ne16
def _ne16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand != 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') # Resets carry flag output.append('sbc hl, de') output.append('ld a, h') output.append('or l') output.append('push af') return output
python
def _ne16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand != 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') # Resets carry flag output.append('sbc hl, de') output.append('ld a, h') output.append('or l') output.append('push af') return output
[ "def", "_ne16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'or a'", ")", "# Resets carry flag", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'or l'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand != 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit un/signed version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "!", "=", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L620-L634
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_or16
def _or16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand OR (logical) 2nd operand (top of the stack), pushes 0 if False, 1 if True. 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) if op2 == 0: output = _16bit_oper(op1) output.append('ld a, h') output.append('or l') # Convert x to Boolean output.append('push af') return output # X or False = X output = _16bit_oper(op1) output.append('ld a, 0FFh') # X or True = True output.append('push af') return output output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('ld a, h') output.append('or l') output.append('or d') output.append('or e') output.append('push af') return output
python
def _or16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand OR (logical) 2nd operand (top of the stack), pushes 0 if False, 1 if True. 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) if op2 == 0: output = _16bit_oper(op1) output.append('ld a, h') output.append('or l') # Convert x to Boolean output.append('push af') return output # X or False = X output = _16bit_oper(op1) output.append('ld a, 0FFh') # X or True = True output.append('push af') return output output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('ld a, h') output.append('or l') output.append('or d') output.append('or e') output.append('push af') return output
[ "def", "_or16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", "is", "not", "None", ":", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "if", "op2", "==", "0", ":", "output", "=", "_16bit_oper", "(", "op1", ")", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'or l'", ")", "# Convert x to Boolean", "output", ".", "append", "(", "'push af'", ")", "return", "output", "# X or False = X", "output", "=", "_16bit_oper", "(", "op1", ")", "output", ".", "append", "(", "'ld a, 0FFh'", ")", "# X or True = True", "output", ".", "append", "(", "'push af'", ")", "return", "output", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'or l'", ")", "output", ".", "append", "(", "'or d'", ")", "output", ".", "append", "(", "'or e'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Compares & pops top 2 operands out of the stack, and checks if the 1st operand OR (logical) 2nd operand (top of the stack), pushes 0 if False, 1 if True. 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", "OR", "(", "logical", ")", "2nd", "operand", "(", "top", "of", "the", "stack", ")", "pushes", "0", "if", "False", "1", "if", "True", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L637-L672
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_bor16
def _bor16(ins): ''' Pops top 2 operands out of the stack, and performs 1st operand OR (bitwise) 2nd operand (top of the stack), pushes result (16 bit in HL). 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) output = _16bit_oper(op1) if op2 == 0: # X | 0 = X output.append('push hl') return output if op2 == 0xFFFF: # X & 0xFFFF = 0xFFFF output.append('ld hl, 0FFFFh') output.append('push hl') return output output = _16bit_oper(op1, op2) output.append('call __BOR16') output.append('push hl') REQUIRES.add('bor16.asm') return output
python
def _bor16(ins): ''' Pops top 2 operands out of the stack, and performs 1st operand OR (bitwise) 2nd operand (top of the stack), pushes result (16 bit in HL). 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) output = _16bit_oper(op1) if op2 == 0: # X | 0 = X output.append('push hl') return output if op2 == 0xFFFF: # X & 0xFFFF = 0xFFFF output.append('ld hl, 0FFFFh') output.append('push hl') return output output = _16bit_oper(op1, op2) output.append('call __BOR16') output.append('push hl') REQUIRES.add('bor16.asm') return output
[ "def", "_bor16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", "is", "not", "None", ":", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "# X | 0 = X", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "==", "0xFFFF", ":", "# X & 0xFFFF = 0xFFFF", "output", ".", "append", "(", "'ld hl, 0FFFFh'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'call __BOR16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'bor16.asm'", ")", "return", "output" ]
Pops top 2 operands out of the stack, and performs 1st operand OR (bitwise) 2nd operand (top of the stack), pushes result (16 bit in HL). 16 bit un/signed version Optimizations: If any of the operators are constants: Returns either 0 or the other operand
[ "Pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "performs", "1st", "operand", "OR", "(", "bitwise", ")", "2nd", "operand", "(", "top", "of", "the", "stack", ")", "pushes", "result", "(", "16", "bit", "in", "HL", ")", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L675-L706
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_not16
def _not16(ins): ''' Negates top (Logical NOT) of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('ld a, h') output.append('or l') output.append('sub 1') output.append('sbc a, a') output.append('push af') return output
python
def _not16(ins): ''' Negates top (Logical NOT) of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('ld a, h') output.append('or l') output.append('sub 1') output.append('sbc a, a') output.append('push af') return output
[ "def", "_not16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'or l'", ")", "output", ".", "append", "(", "'sub 1'", ")", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Negates top (Logical NOT) of the stack (16 bits in HL)
[ "Negates", "top", "(", "Logical", "NOT", ")", "of", "the", "stack", "(", "16", "bits", "in", "HL", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L852-L861
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_bnot16
def _bnot16(ins): ''' Negates top (Bitwise NOT) of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __BNOT16') output.append('push hl') REQUIRES.add('bnot16.asm') return output
python
def _bnot16(ins): ''' Negates top (Bitwise NOT) of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __BNOT16') output.append('push hl') REQUIRES.add('bnot16.asm') return output
[ "def", "_bnot16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'call __BNOT16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'bnot16.asm'", ")", "return", "output" ]
Negates top (Bitwise NOT) of the stack (16 bits in HL)
[ "Negates", "top", "(", "Bitwise", "NOT", ")", "of", "the", "stack", "(", "16", "bits", "in", "HL", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L864-L871
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_neg16
def _neg16(ins): ''' Negates top of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output
python
def _neg16(ins): ''' Negates top of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output
[ "def", "_neg16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'call __NEGHL'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'neg16.asm'", ")", "return", "output" ]
Negates top of the stack (16 bits in HL)
[ "Negates", "top", "of", "the", "stack", "(", "16", "bits", "in", "HL", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L874-L881
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_abs16
def _abs16(ins): ''' Absolute value of top of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __ABS16') output.append('push hl') REQUIRES.add('abs16.asm') return output
python
def _abs16(ins): ''' Absolute value of top of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __ABS16') output.append('push hl') REQUIRES.add('abs16.asm') return output
[ "def", "_abs16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'call __ABS16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'abs16.asm'", ")", "return", "output" ]
Absolute value of top of the stack (16 bits in HL)
[ "Absolute", "value", "of", "top", "of", "the", "stack", "(", "16", "bits", "in", "HL", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L884-L891
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_shru16
def _shru16(ins): ''' Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld b, %i' % op) else: output = _8bit_oper(op2) output.append('ld b, a') output.extend(_16bit_oper(op1)) label = tmp_label() output.append('%s:' % label) output.append('srl h') output.append('rr l') output.append('djnz %s' % label) output.append('push hl') return output
python
def _shru16(ins): ''' Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld b, %i' % op) else: output = _8bit_oper(op2) output.append('ld b, a') output.extend(_16bit_oper(op1)) label = tmp_label() output.append('%s:' % label) output.append('srl h') output.append('rr l') output.append('djnz %s' % label) output.append('push hl') return output
[ "def", "_shru16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "if", "op", "==", "0", ":", "return", "[", "]", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op", "==", "1", ":", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld b, %i'", "%", "op", ")", "else", ":", "output", "=", "_8bit_oper", "(", "op2", ")", "output", ".", "append", "(", "'ld b, a'", ")", "output", ".", "extend", "(", "_16bit_oper", "(", "op1", ")", ")", "label", "=", "tmp_label", "(", ")", "output", ".", "append", "(", "'%s:'", "%", "label", ")", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'djnz %s'", "%", "label", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic
[ "Logical", "right", "shift", "16bit", "unsigned", "integer", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L894-L930
boriel/zxbasic
outfmt/tap.py
TAP.standard_block
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)
python
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)
[ "def", "standard_block", "(", "self", ",", "bytes_", ")", ":", "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", ")" ]
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)
[ "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", ")" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tap.py#L28-L39
boriel/zxbasic
api/utils.py
read_txt_file
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) if six.PY2: result = result.encode('utf-8') return result except UnicodeDecodeError: pass global_.FILENAME = fname errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings)) return ''
python
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) if six.PY2: result = result.encode('utf-8') return result except UnicodeDecodeError: pass global_.FILENAME = fname errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings)) return ''
[ "def", "read_txt_file", "(", "fname", ")", ":", "encodings", "=", "[", "'utf-8-sig'", ",", "'cp1252'", "]", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "f", ":", "content", "=", "bytes", "(", "f", ".", "read", "(", ")", ")", "for", "i", "in", "encodings", ":", "try", ":", "result", "=", "content", ".", "decode", "(", "i", ")", "if", "six", ".", "PY2", ":", "result", "=", "result", ".", "encode", "(", "'utf-8'", ")", "return", "result", "except", "UnicodeDecodeError", ":", "pass", "global_", ".", "FILENAME", "=", "fname", "errmsg", ".", "syntax_error", "(", "1", ",", "'Invalid file encoding. Use one of: %s'", "%", "', '", ".", "join", "(", "encodings", ")", ")", "return", "''" ]
Reads a txt file, regardless of its encoding
[ "Reads", "a", "txt", "file", "regardless", "of", "its", "encoding" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/utils.py#L15-L33
boriel/zxbasic
api/utils.py
open_file
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 six.PY2 or 't' not in mode: kwargs = {} else: kwargs = {'encoding': encoding} return open(fname, mode, **kwargs)
python
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 six.PY2 or 't' not in mode: kwargs = {} else: kwargs = {'encoding': encoding} return open(fname, mode, **kwargs)
[ "def", "open_file", "(", "fname", ",", "mode", "=", "'rb'", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "six", ".", "PY2", "or", "'t'", "not", "in", "mode", ":", "kwargs", "=", "{", "}", "else", ":", "kwargs", "=", "{", "'encoding'", ":", "encoding", "}", "return", "open", "(", "fname", ",", "mode", ",", "*", "*", "kwargs", ")" ]
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
[ "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" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/utils.py#L36-L48
boriel/zxbasic
api/utils.py
parse_int
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
python
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", "parse_int", "(", "str_num", ")", ":", "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" ]
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
[ "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" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/utils.py#L77-L102
boriel/zxbasic
outfmt/tzx.py
TZX.out
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])
python
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", "out", "(", "self", ",", "l", ")", ":", "if", "not", "isinstance", "(", "l", ",", "list", ")", ":", "l", "=", "[", "l", "]", "self", ".", "output", ".", "extend", "(", "[", "int", "(", "i", ")", "&", "0xFF", "for", "i", "in", "l", "]", ")" ]
Adds a list of bytes to the output string
[ "Adds", "a", "list", "of", "bytes", "to", "the", "output", "string" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L52-L58
boriel/zxbasic
outfmt/tzx.py
TZX.standard_block
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)
python
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", "standard_block", "(", "self", ",", "_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", ")" ]
Adds a standard block of bytes
[ "Adds", "a", "standard", "block", "of", "bytes" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L60-L72
boriel/zxbasic
outfmt/tzx.py
TZX.dump
def dump(self, fname): """ Saves TZX file to fname """ with open(fname, 'wb') as f: f.write(self.output)
python
def dump(self, fname): """ Saves TZX file to fname """ with open(fname, 'wb') as f: f.write(self.output)
[ "def", "dump", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "output", ")" ]
Saves TZX file to fname
[ "Saves", "TZX", "file", "to", "fname" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L74-L78
boriel/zxbasic
outfmt/tzx.py
TZX.save_header
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)
python
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", "save_header", "(", "self", ",", "_type", ",", "title", ",", "length", ",", "param1", ",", "param2", ")", ":", "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", ")" ]
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
[ "Saves", "a", "generic", "standard", "header", ":", "type", ":", "00", "--", "Program", "01", "--", "Number", "Array", "02", "--", "Char", "Array", "03", "--", "Code" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L80-L107
boriel/zxbasic
outfmt/tzx.py
TZX.standard_bytes_header
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)
python
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_bytes_header", "(", "self", ",", "title", ",", "addr", ",", "length", ")", ":", "self", ".", "save_header", "(", "self", ".", "HEADER_TYPE_CODE", ",", "title", ",", "length", ",", "param1", "=", "addr", ",", "param2", "=", "32768", ")" ]
Generates a standard header block of CODE type
[ "Generates", "a", "standard", "header", "block", "of", "CODE", "type" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L109-L112
boriel/zxbasic
outfmt/tzx.py
TZX.standard_program_header
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)
python
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", "standard_program_header", "(", "self", ",", "title", ",", "length", ",", "line", "=", "32768", ")", ":", "self", ".", "save_header", "(", "self", ".", "HEADER_TYPE_BASIC", ",", "title", ",", "length", ",", "param1", "=", "line", ",", "param2", "=", "length", ")" ]
Generates a standard header block of PROGRAM type
[ "Generates", "a", "standard", "header", "block", "of", "PROGRAM", "type" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L114-L117
boriel/zxbasic
outfmt/tzx.py
TZX.save_code
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)
python
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_code", "(", "self", ",", "title", ",", "addr", ",", "_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", ")" ]
Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes
[ "Saves", "the", "given", "bytes", "as", "code", ".", "If", "bytes", "are", "strings", "its", "chars", "will", "be", "converted", "to", "bytes" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L119-L125
boriel/zxbasic
outfmt/tzx.py
TZX.save_program
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)
python
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", "save_program", "(", "self", ",", "title", ",", "bytes", ",", "line", "=", "32768", ")", ":", "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", ")" ]
Saves the given bytes as a BASIC program.
[ "Saves", "the", "given", "bytes", "as", "a", "BASIC", "program", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L127-L132
boriel/zxbasic
symbols/strslice.py
SymbolSTRSLICE.make_node
def make_node(cls, lineno, s, lower, upper): """ Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned. """ if lower is None or upper is None or s is None: return None if not check_type(lineno, Type.string, s): return None lo = up = None base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno) lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', lower, base, lineno=lineno, func=lambda x, y: x - y), lineno) upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', upper, base, lineno=lineno, func=lambda x, y: x - y), lineno) if lower is None or upper is None: return None if is_number(lower): lo = lower.value if lo < gl.MIN_STRSLICE_IDX: lower.value = lo = gl.MIN_STRSLICE_IDX if is_number(upper): up = upper.value if up > gl.MAX_STRSLICE_IDX: upper.value = up = gl.MAX_STRSLICE_IDX if is_number(lower, upper): if lo > up: return STRING('', lineno) if s.token == 'STRING': # A constant string? Recalculate it now up += 1 st = s.value.ljust(up) # Procrustean filled (right) return STRING(st[lo:up], lineno) # a$(0 TO INF.) = a$ if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX: return s return cls(s, lower, upper, lineno)
python
def make_node(cls, lineno, s, lower, upper): """ Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned. """ if lower is None or upper is None or s is None: return None if not check_type(lineno, Type.string, s): return None lo = up = None base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno) lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', lower, base, lineno=lineno, func=lambda x, y: x - y), lineno) upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', upper, base, lineno=lineno, func=lambda x, y: x - y), lineno) if lower is None or upper is None: return None if is_number(lower): lo = lower.value if lo < gl.MIN_STRSLICE_IDX: lower.value = lo = gl.MIN_STRSLICE_IDX if is_number(upper): up = upper.value if up > gl.MAX_STRSLICE_IDX: upper.value = up = gl.MAX_STRSLICE_IDX if is_number(lower, upper): if lo > up: return STRING('', lineno) if s.token == 'STRING': # A constant string? Recalculate it now up += 1 st = s.value.ljust(up) # Procrustean filled (right) return STRING(st[lo:up], lineno) # a$(0 TO INF.) = a$ if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX: return s return cls(s, lower, upper, lineno)
[ "def", "make_node", "(", "cls", ",", "lineno", ",", "s", ",", "lower", ",", "upper", ")", ":", "if", "lower", "is", "None", "or", "upper", "is", "None", "or", "s", "is", "None", ":", "return", "None", "if", "not", "check_type", "(", "lineno", ",", "Type", ".", "string", ",", "s", ")", ":", "return", "None", "lo", "=", "up", "=", "None", "base", "=", "NUMBER", "(", "api", ".", "config", ".", "OPTIONS", ".", "string_base", ".", "value", ",", "lineno", "=", "lineno", ")", "lower", "=", "TYPECAST", ".", "make_node", "(", "gl", ".", "SYMBOL_TABLE", ".", "basic_types", "[", "gl", ".", "STR_INDEX_TYPE", "]", ",", "BINARY", ".", "make_node", "(", "'MINUS'", ",", "lower", ",", "base", ",", "lineno", "=", "lineno", ",", "func", "=", "lambda", "x", ",", "y", ":", "x", "-", "y", ")", ",", "lineno", ")", "upper", "=", "TYPECAST", ".", "make_node", "(", "gl", ".", "SYMBOL_TABLE", ".", "basic_types", "[", "gl", ".", "STR_INDEX_TYPE", "]", ",", "BINARY", ".", "make_node", "(", "'MINUS'", ",", "upper", ",", "base", ",", "lineno", "=", "lineno", ",", "func", "=", "lambda", "x", ",", "y", ":", "x", "-", "y", ")", ",", "lineno", ")", "if", "lower", "is", "None", "or", "upper", "is", "None", ":", "return", "None", "if", "is_number", "(", "lower", ")", ":", "lo", "=", "lower", ".", "value", "if", "lo", "<", "gl", ".", "MIN_STRSLICE_IDX", ":", "lower", ".", "value", "=", "lo", "=", "gl", ".", "MIN_STRSLICE_IDX", "if", "is_number", "(", "upper", ")", ":", "up", "=", "upper", ".", "value", "if", "up", ">", "gl", ".", "MAX_STRSLICE_IDX", ":", "upper", ".", "value", "=", "up", "=", "gl", ".", "MAX_STRSLICE_IDX", "if", "is_number", "(", "lower", ",", "upper", ")", ":", "if", "lo", ">", "up", ":", "return", "STRING", "(", "''", ",", "lineno", ")", "if", "s", ".", "token", "==", "'STRING'", ":", "# A constant string? Recalculate it now", "up", "+=", "1", "st", "=", "s", ".", "value", ".", "ljust", "(", "up", ")", "# Procrustean filled (right)", "return", "STRING", "(", "st", "[", "lo", ":", "up", "]", ",", "lineno", ")", "# a$(0 TO INF.) = a$", "if", "lo", "==", "gl", ".", "MIN_STRSLICE_IDX", "and", "up", "==", "gl", ".", "MAX_STRSLICE_IDX", ":", "return", "s", "return", "cls", "(", "s", ",", "lower", ",", "upper", ",", "lineno", ")" ]
Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned.
[ "Creates", "a", "node", "for", "a", "string", "slice", ".", "S", "is", "the", "string", "expression", "Tree", ".", "Lower", "and", "upper", "are", "the", "bounds", "if", "lower", "&", "upper", "are", "constants", "and", "s", "is", "also", "constant", "then", "a", "string", "constant", "is", "returned", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/strslice.py#L69-L117
boriel/zxbasic
arch/zx48k/backend/__init__.py
init
def init(): """ Initializes this module """ global ASMS global ASMCOUNT global AT_END global FLAG_end_emitted global FLAG_use_function_exit __common.init() ASMS = {} ASMCOUNT = 0 AT_END = [] FLAG_use_function_exit = False FLAG_end_emitted = False # Default code ORG OPTIONS.add_option('org', int, 32768) # Default HEAP SIZE (Dynamic memory) in bytes OPTIONS.add_option('heap_size', int, 4768) # A bit more than 4K # Labels for HEAP START (might not be used if not needed) OPTIONS.add_option('heap_start_label', str, 'ZXBASIC_MEM_HEAP') # Labels for HEAP SIZE (might not be used if not needed) OPTIONS.add_option('heap_size_label', str, 'ZXBASIC_HEAP_SIZE') # Flag for headerless mode (No prologue / epilogue) OPTIONS.add_option('headerless', bool, False)
python
def init(): """ Initializes this module """ global ASMS global ASMCOUNT global AT_END global FLAG_end_emitted global FLAG_use_function_exit __common.init() ASMS = {} ASMCOUNT = 0 AT_END = [] FLAG_use_function_exit = False FLAG_end_emitted = False # Default code ORG OPTIONS.add_option('org', int, 32768) # Default HEAP SIZE (Dynamic memory) in bytes OPTIONS.add_option('heap_size', int, 4768) # A bit more than 4K # Labels for HEAP START (might not be used if not needed) OPTIONS.add_option('heap_start_label', str, 'ZXBASIC_MEM_HEAP') # Labels for HEAP SIZE (might not be used if not needed) OPTIONS.add_option('heap_size_label', str, 'ZXBASIC_HEAP_SIZE') # Flag for headerless mode (No prologue / epilogue) OPTIONS.add_option('headerless', bool, False)
[ "def", "init", "(", ")", ":", "global", "ASMS", "global", "ASMCOUNT", "global", "AT_END", "global", "FLAG_end_emitted", "global", "FLAG_use_function_exit", "__common", ".", "init", "(", ")", "ASMS", "=", "{", "}", "ASMCOUNT", "=", "0", "AT_END", "=", "[", "]", "FLAG_use_function_exit", "=", "False", "FLAG_end_emitted", "=", "False", "# Default code ORG", "OPTIONS", ".", "add_option", "(", "'org'", ",", "int", ",", "32768", ")", "# Default HEAP SIZE (Dynamic memory) in bytes", "OPTIONS", ".", "add_option", "(", "'heap_size'", ",", "int", ",", "4768", ")", "# A bit more than 4K", "# Labels for HEAP START (might not be used if not needed)", "OPTIONS", ".", "add_option", "(", "'heap_start_label'", ",", "str", ",", "'ZXBASIC_MEM_HEAP'", ")", "# Labels for HEAP SIZE (might not be used if not needed)", "OPTIONS", ".", "add_option", "(", "'heap_size_label'", ",", "str", ",", "'ZXBASIC_HEAP_SIZE'", ")", "# Flag for headerless mode (No prologue / epilogue)", "OPTIONS", ".", "add_option", "(", "'headerless'", ",", "bool", ",", "False", ")" ]
Initializes this module
[ "Initializes", "this", "module" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L189-L215
boriel/zxbasic
arch/zx48k/backend/__init__.py
to_byte
def to_byte(stype): """ Returns the instruction sequence for converting from the given type to byte. """ output = [] if stype in ('i8', 'u8'): return [] if is_int_type(stype): output.append('ld a, l') elif stype == 'f16': output.append('ld a, e') elif stype == 'f': # Converts C ED LH to byte output.append('call __FTOU32REG') output.append('ld a, l') REQUIRES.add('ftou32reg.asm') return output
python
def to_byte(stype): """ Returns the instruction sequence for converting from the given type to byte. """ output = [] if stype in ('i8', 'u8'): return [] if is_int_type(stype): output.append('ld a, l') elif stype == 'f16': output.append('ld a, e') elif stype == 'f': # Converts C ED LH to byte output.append('call __FTOU32REG') output.append('ld a, l') REQUIRES.add('ftou32reg.asm') return output
[ "def", "to_byte", "(", "stype", ")", ":", "output", "=", "[", "]", "if", "stype", "in", "(", "'i8'", ",", "'u8'", ")", ":", "return", "[", "]", "if", "is_int_type", "(", "stype", ")", ":", "output", ".", "append", "(", "'ld a, l'", ")", "elif", "stype", "==", "'f16'", ":", "output", ".", "append", "(", "'ld a, e'", ")", "elif", "stype", "==", "'f'", ":", "# Converts C ED LH to byte", "output", ".", "append", "(", "'call __FTOU32REG'", ")", "output", ".", "append", "(", "'ld a, l'", ")", "REQUIRES", ".", "add", "(", "'ftou32reg.asm'", ")", "return", "output" ]
Returns the instruction sequence for converting from the given type to byte.
[ "Returns", "the", "instruction", "sequence", "for", "converting", "from", "the", "given", "type", "to", "byte", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L252-L270
boriel/zxbasic
arch/zx48k/backend/__init__.py
to_word
def to_word(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to word (unsigned) HL. """ output = [] # List of instructions if stype == 'u8': # Byte to word output.append('ld l, a') output.append('ld h, 0') elif stype == 'i8': # Signed byte to word output.append('ld l, a') output.append('add a, a') output.append('sbc a, a') output.append('ld h, a') elif stype == 'f16': # Must MOVE HL into DE output.append('ex de, hl') elif stype == 'f': output.append('call __FTOU32REG') REQUIRES.add('ftou32reg.asm') return output
python
def to_word(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to word (unsigned) HL. """ output = [] # List of instructions if stype == 'u8': # Byte to word output.append('ld l, a') output.append('ld h, 0') elif stype == 'i8': # Signed byte to word output.append('ld l, a') output.append('add a, a') output.append('sbc a, a') output.append('ld h, a') elif stype == 'f16': # Must MOVE HL into DE output.append('ex de, hl') elif stype == 'f': output.append('call __FTOU32REG') REQUIRES.add('ftou32reg.asm') return output
[ "def", "to_word", "(", "stype", ")", ":", "output", "=", "[", "]", "# List of instructions", "if", "stype", "==", "'u8'", ":", "# Byte to word", "output", ".", "append", "(", "'ld l, a'", ")", "output", ".", "append", "(", "'ld h, 0'", ")", "elif", "stype", "==", "'i8'", ":", "# Signed byte to word", "output", ".", "append", "(", "'ld l, a'", ")", "output", ".", "append", "(", "'add a, a'", ")", "output", ".", "append", "(", "'sbc a, a'", ")", "output", ".", "append", "(", "'ld h, a'", ")", "elif", "stype", "==", "'f16'", ":", "# Must MOVE HL into DE", "output", ".", "append", "(", "'ex de, hl'", ")", "elif", "stype", "==", "'f'", ":", "output", ".", "append", "(", "'call __FTOU32REG'", ")", "REQUIRES", ".", "add", "(", "'ftou32reg.asm'", ")", "return", "output" ]
Returns the instruction sequence for converting the given type stored in DE,HL to word (unsigned) HL.
[ "Returns", "the", "instruction", "sequence", "for", "converting", "the", "given", "type", "stored", "in", "DE", "HL", "to", "word", "(", "unsigned", ")", "HL", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L273-L296
boriel/zxbasic
arch/zx48k/backend/__init__.py
to_fixed
def to_fixed(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL. """ output = [] # List of instructions if is_int_type(stype): output = to_word(stype) output.append('ex de, hl') output.append('ld hl, 0') # 'Truncate' the fixed point elif stype == 'f': output.append('call __FTOF16REG') REQUIRES.add('ftof16reg.asm') return output
python
def to_fixed(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL. """ output = [] # List of instructions if is_int_type(stype): output = to_word(stype) output.append('ex de, hl') output.append('ld hl, 0') # 'Truncate' the fixed point elif stype == 'f': output.append('call __FTOF16REG') REQUIRES.add('ftof16reg.asm') return output
[ "def", "to_fixed", "(", "stype", ")", ":", "output", "=", "[", "]", "# List of instructions", "if", "is_int_type", "(", "stype", ")", ":", "output", "=", "to_word", "(", "stype", ")", "output", ".", "append", "(", "'ex de, hl'", ")", "output", ".", "append", "(", "'ld hl, 0'", ")", "# 'Truncate' the fixed point", "elif", "stype", "==", "'f'", ":", "output", ".", "append", "(", "'call __FTOF16REG'", ")", "REQUIRES", ".", "add", "(", "'ftof16reg.asm'", ")", "return", "output" ]
Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL.
[ "Returns", "the", "instruction", "sequence", "for", "converting", "the", "given", "type", "stored", "in", "DE", "HL", "to", "fixed", "DE", "HL", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L329-L343
boriel/zxbasic
arch/zx48k/backend/__init__.py
to_float
def to_float(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL. """ output = [] # List of instructions if stype == 'f': return [] # Nothing to do if stype == 'f16': output.append('call __F16TOFREG') REQUIRES.add('f16tofreg.asm') return output # If we reach this point, it's an integer type if stype == 'u8': output.append('call __U8TOFREG') elif stype == 'i8': output.append('call __I8TOFREG') else: output = to_long(stype) if stype in ('i16', 'i32'): output.append('call __I32TOFREG') else: output.append('call __U32TOFREG') REQUIRES.add('u32tofreg.asm') return output
python
def to_float(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL. """ output = [] # List of instructions if stype == 'f': return [] # Nothing to do if stype == 'f16': output.append('call __F16TOFREG') REQUIRES.add('f16tofreg.asm') return output # If we reach this point, it's an integer type if stype == 'u8': output.append('call __U8TOFREG') elif stype == 'i8': output.append('call __I8TOFREG') else: output = to_long(stype) if stype in ('i16', 'i32'): output.append('call __I32TOFREG') else: output.append('call __U32TOFREG') REQUIRES.add('u32tofreg.asm') return output
[ "def", "to_float", "(", "stype", ")", ":", "output", "=", "[", "]", "# List of instructions", "if", "stype", "==", "'f'", ":", "return", "[", "]", "# Nothing to do", "if", "stype", "==", "'f16'", ":", "output", ".", "append", "(", "'call __F16TOFREG'", ")", "REQUIRES", ".", "add", "(", "'f16tofreg.asm'", ")", "return", "output", "# If we reach this point, it's an integer type", "if", "stype", "==", "'u8'", ":", "output", ".", "append", "(", "'call __U8TOFREG'", ")", "elif", "stype", "==", "'i8'", ":", "output", ".", "append", "(", "'call __I8TOFREG'", ")", "else", ":", "output", "=", "to_long", "(", "stype", ")", "if", "stype", "in", "(", "'i16'", ",", "'i32'", ")", ":", "output", ".", "append", "(", "'call __I32TOFREG'", ")", "else", ":", "output", ".", "append", "(", "'call __U32TOFREG'", ")", "REQUIRES", ".", "add", "(", "'u32tofreg.asm'", ")", "return", "output" ]
Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL.
[ "Returns", "the", "instruction", "sequence", "for", "converting", "the", "given", "type", "stored", "in", "DE", "HL", "to", "fixed", "DE", "HL", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L346-L374
boriel/zxbasic
arch/zx48k/backend/__init__.py
_end
def _end(ins): """ Outputs the ending sequence """ global FLAG_end_emitted output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') if FLAG_end_emitted: return output + ['jp %s' % END_LABEL] FLAG_end_emitted = True output.append('%s:' % END_LABEL) if OPTIONS.headerless.value: return output + ['ret'] output.append('di') output.append('ld hl, (%s)' % CALL_BACK) output.append('ld sp, hl') output.append('exx') output.append('pop hl') output.append('exx') output.append('pop iy') output.append('pop ix') output.append('ei') output.append('ret') output.append('%s:' % CALL_BACK) output.append('DEFW 0') return output
python
def _end(ins): """ Outputs the ending sequence """ global FLAG_end_emitted output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') if FLAG_end_emitted: return output + ['jp %s' % END_LABEL] FLAG_end_emitted = True output.append('%s:' % END_LABEL) if OPTIONS.headerless.value: return output + ['ret'] output.append('di') output.append('ld hl, (%s)' % CALL_BACK) output.append('ld sp, hl') output.append('exx') output.append('pop hl') output.append('exx') output.append('pop iy') output.append('pop ix') output.append('ei') output.append('ret') output.append('%s:' % CALL_BACK) output.append('DEFW 0') return output
[ "def", "_end", "(", "ins", ")", ":", "global", "FLAG_end_emitted", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'ld b, h'", ")", "output", ".", "append", "(", "'ld c, l'", ")", "if", "FLAG_end_emitted", ":", "return", "output", "+", "[", "'jp %s'", "%", "END_LABEL", "]", "FLAG_end_emitted", "=", "True", "output", ".", "append", "(", "'%s:'", "%", "END_LABEL", ")", "if", "OPTIONS", ".", "headerless", ".", "value", ":", "return", "output", "+", "[", "'ret'", "]", "output", ".", "append", "(", "'di'", ")", "output", ".", "append", "(", "'ld hl, (%s)'", "%", "CALL_BACK", ")", "output", ".", "append", "(", "'ld sp, hl'", ")", "output", ".", "append", "(", "'exx'", ")", "output", ".", "append", "(", "'pop hl'", ")", "output", ".", "append", "(", "'exx'", ")", "output", ".", "append", "(", "'pop iy'", ")", "output", ".", "append", "(", "'pop ix'", ")", "output", ".", "append", "(", "'ei'", ")", "output", ".", "append", "(", "'ret'", ")", "output", ".", "append", "(", "'%s:'", "%", "CALL_BACK", ")", "output", ".", "append", "(", "'DEFW 0'", ")", "return", "output" ]
Outputs the ending sequence
[ "Outputs", "the", "ending", "sequence" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L403-L433
boriel/zxbasic
arch/zx48k/backend/__init__.py
_data
def _data(ins): """ Defines a data item (binary). It's just a constant expression to be converted do binary data "as is" 1st parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc) 2nd parameter is the list of expressions. All of them will be converted to the type required. """ output = [] t = ins.quad[1] q = eval(ins.quad[2]) if t in ('i8', 'u8'): size = 'B' elif t in ('i16', 'u16'): size = 'W' elif t in ('i32', 'u32'): size = 'W' z = list() for expr in ins.quad[2]: z.extend(['(%s) & 0xFFFF' % expr, '(%s) >> 16' % expr]) q = z elif t == 'str': size = "B" q = ['"%s"' % x.replace('"', '""') for x in q] elif t == 'f': dat_ = [api.fp.immediate_float(float(x)) for x in q] for x in dat_: output.extend(['DEFB %s' % x[0], 'DEFW %s, %s' % (x[1], x[2])]) return output else: raise InvalidIC(ins.quad, 'Unimplemented data size %s for %s' % (t, q)) for x in q: output.append('DEF%s %s' % (size, x)) return output
python
def _data(ins): """ Defines a data item (binary). It's just a constant expression to be converted do binary data "as is" 1st parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc) 2nd parameter is the list of expressions. All of them will be converted to the type required. """ output = [] t = ins.quad[1] q = eval(ins.quad[2]) if t in ('i8', 'u8'): size = 'B' elif t in ('i16', 'u16'): size = 'W' elif t in ('i32', 'u32'): size = 'W' z = list() for expr in ins.quad[2]: z.extend(['(%s) & 0xFFFF' % expr, '(%s) >> 16' % expr]) q = z elif t == 'str': size = "B" q = ['"%s"' % x.replace('"', '""') for x in q] elif t == 'f': dat_ = [api.fp.immediate_float(float(x)) for x in q] for x in dat_: output.extend(['DEFB %s' % x[0], 'DEFW %s, %s' % (x[1], x[2])]) return output else: raise InvalidIC(ins.quad, 'Unimplemented data size %s for %s' % (t, q)) for x in q: output.append('DEF%s %s' % (size, x)) return output
[ "def", "_data", "(", "ins", ")", ":", "output", "=", "[", "]", "t", "=", "ins", ".", "quad", "[", "1", "]", "q", "=", "eval", "(", "ins", ".", "quad", "[", "2", "]", ")", "if", "t", "in", "(", "'i8'", ",", "'u8'", ")", ":", "size", "=", "'B'", "elif", "t", "in", "(", "'i16'", ",", "'u16'", ")", ":", "size", "=", "'W'", "elif", "t", "in", "(", "'i32'", ",", "'u32'", ")", ":", "size", "=", "'W'", "z", "=", "list", "(", ")", "for", "expr", "in", "ins", ".", "quad", "[", "2", "]", ":", "z", ".", "extend", "(", "[", "'(%s) & 0xFFFF'", "%", "expr", ",", "'(%s) >> 16'", "%", "expr", "]", ")", "q", "=", "z", "elif", "t", "==", "'str'", ":", "size", "=", "\"B\"", "q", "=", "[", "'\"%s\"'", "%", "x", ".", "replace", "(", "'\"'", ",", "'\"\"'", ")", "for", "x", "in", "q", "]", "elif", "t", "==", "'f'", ":", "dat_", "=", "[", "api", ".", "fp", ".", "immediate_float", "(", "float", "(", "x", ")", ")", "for", "x", "in", "q", "]", "for", "x", "in", "dat_", ":", "output", ".", "extend", "(", "[", "'DEFB %s'", "%", "x", "[", "0", "]", ",", "'DEFW %s, %s'", "%", "(", "x", "[", "1", "]", ",", "x", "[", "2", "]", ")", "]", ")", "return", "output", "else", ":", "raise", "InvalidIC", "(", "ins", ".", "quad", ",", "'Unimplemented data size %s for %s'", "%", "(", "t", ",", "q", ")", ")", "for", "x", "in", "q", ":", "output", ".", "append", "(", "'DEF%s %s'", "%", "(", "size", ",", "x", ")", ")", "return", "output" ]
Defines a data item (binary). It's just a constant expression to be converted do binary data "as is" 1st parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc) 2nd parameter is the list of expressions. All of them will be converted to the type required.
[ "Defines", "a", "data", "item", "(", "binary", ")", ".", "It", "s", "just", "a", "constant", "expression", "to", "be", "converted", "do", "binary", "data", "as", "is" ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L448-L484
boriel/zxbasic
arch/zx48k/backend/__init__.py
_var
def _var(ins): """ Defines a memory variable. """ output = [] output.append('%s:' % ins.quad[1]) output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00')) return output
python
def _var(ins): """ Defines a memory variable. """ output = [] output.append('%s:' % ins.quad[1]) output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00')) return output
[ "def", "_var", "(", "ins", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "'%s:'", "%", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'DEFB %s'", "%", "(", "(", "int", "(", "ins", ".", "quad", "[", "2", "]", ")", "-", "1", ")", "*", "'00, '", "+", "'00'", ")", ")", "return", "output" ]
Defines a memory variable.
[ "Defines", "a", "memory", "variable", "." ]
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L487-L494