repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
boriel/zxbasic | zxbparser.py | p_function_def | def p_function_def(p):
""" function_def : FUNCTION convention ID
| SUB convention ID
"""
p[0] = make_func_declaration(p[3], p.lineno(3))
SYMBOL_TABLE.enter_scope(p[3])
FUNCTION_LEVEL.append(SYMBOL_TABLE.get_entry(p[3]))
FUNCTION_LEVEL[-1].convention = p[2]
if p[0] is not None:
kind = KIND.sub if p[1] == 'SUB' else KIND.function # Must be 'function' or 'sub'
FUNCTION_LEVEL[-1].set_kind(kind, p.lineno(1)) | python | def p_function_def(p):
""" function_def : FUNCTION convention ID
| SUB convention ID
"""
p[0] = make_func_declaration(p[3], p.lineno(3))
SYMBOL_TABLE.enter_scope(p[3])
FUNCTION_LEVEL.append(SYMBOL_TABLE.get_entry(p[3]))
FUNCTION_LEVEL[-1].convention = p[2]
if p[0] is not None:
kind = KIND.sub if p[1] == 'SUB' else KIND.function # Must be 'function' or 'sub'
FUNCTION_LEVEL[-1].set_kind(kind, p.lineno(1)) | function_def : FUNCTION convention ID
| SUB convention ID | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2850-L2861 |
boriel/zxbasic | zxbparser.py | p_param_definition | def p_param_definition(p):
""" param_definition : param_def
"""
p[0] = p[1]
if p[0] is not None:
p[0].byref = OPTIONS.byref.value | python | def p_param_definition(p):
""" param_definition : param_def
"""
p[0] = p[1]
if p[0] is not None:
p[0].byref = OPTIONS.byref.value | param_definition : param_def | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2926-L2931 |
boriel/zxbasic | zxbparser.py | p_param_def_type | def p_param_def_type(p):
""" param_def : ID typedef
"""
if p[2] is not None:
api.check.check_type_is_explicit(p.lineno(1), p[1], p[2])
p[0] = make_param_decl(p[1], p.lineno(1), p[2]) | python | def p_param_def_type(p):
""" param_def : ID typedef
"""
if p[2] is not None:
api.check.check_type_is_explicit(p.lineno(1), p[1], p[2])
p[0] = make_param_decl(p[1], p.lineno(1), p[2]) | param_def : ID typedef | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2934-L2939 |
boriel/zxbasic | zxbparser.py | p_function_body | def p_function_body(p):
""" function_body : program_co END FUNCTION
| program_co END SUB
| statements_co END FUNCTION
| statements_co END SUB
| co_statements_co END FUNCTION
| co_statements_co END SUB
| END FUNCTION
| END SUB
"""
if not FUNCTION_LEVEL:
syntax_error(p.lineno(3), "Unexpected token 'END %s'. No Function or Sub has been defined." % p[2])
p[0] = None
return
a = FUNCTION_LEVEL[-1].kind
if a not in (KIND.sub, KIND.function): # This function/sub was not correctly declared, so exit now
p[0] = None
return
i = 2 if p[1] == 'END' else 3
b = p[i].lower()
if a != b:
syntax_error(p.lineno(i), "Unexpected token 'END %s'. Should be 'END %s'" % (b.upper(), a.upper()))
p[0] = None
else:
p[0] = None if p[1] == 'END' else p[1] | python | def p_function_body(p):
""" function_body : program_co END FUNCTION
| program_co END SUB
| statements_co END FUNCTION
| statements_co END SUB
| co_statements_co END FUNCTION
| co_statements_co END SUB
| END FUNCTION
| END SUB
"""
if not FUNCTION_LEVEL:
syntax_error(p.lineno(3), "Unexpected token 'END %s'. No Function or Sub has been defined." % p[2])
p[0] = None
return
a = FUNCTION_LEVEL[-1].kind
if a not in (KIND.sub, KIND.function): # This function/sub was not correctly declared, so exit now
p[0] = None
return
i = 2 if p[1] == 'END' else 3
b = p[i].lower()
if a != b:
syntax_error(p.lineno(i), "Unexpected token 'END %s'. Should be 'END %s'" % (b.upper(), a.upper()))
p[0] = None
else:
p[0] = None if p[1] == 'END' else p[1] | function_body : program_co END FUNCTION
| program_co END SUB
| statements_co END FUNCTION
| statements_co END SUB
| co_statements_co END FUNCTION
| co_statements_co END SUB
| END FUNCTION
| END SUB | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2942-L2969 |
boriel/zxbasic | zxbparser.py | p_type_def_empty | def p_type_def_empty(p):
""" typedef :
""" # Epsilon. Defaults to float
p[0] = make_type(_TYPE(gl.DEFAULT_TYPE).name, p.lexer.lineno, implicit=True) | python | def p_type_def_empty(p):
""" typedef :
""" # Epsilon. Defaults to float
p[0] = make_type(_TYPE(gl.DEFAULT_TYPE).name, p.lexer.lineno, implicit=True) | typedef : | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2972-L2975 |
boriel/zxbasic | zxbparser.py | p_expr_usr | def p_expr_usr(p):
""" bexpr : USR bexpr %prec UMINUS
"""
if p[2].type_ == TYPE.string:
p[0] = make_builtin(p.lineno(1), 'USR_STR', p[2], type_=TYPE.uinteger)
else:
p[0] = make_builtin(p.lineno(1), 'USR',
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
type_=TYPE.uinteger) | python | def p_expr_usr(p):
""" bexpr : USR bexpr %prec UMINUS
"""
if p[2].type_ == TYPE.string:
p[0] = make_builtin(p.lineno(1), 'USR_STR', p[2], type_=TYPE.uinteger)
else:
p[0] = make_builtin(p.lineno(1), 'USR',
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
type_=TYPE.uinteger) | bexpr : USR bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3056-L3064 |
boriel/zxbasic | zxbparser.py | p_expr_peek | def p_expr_peek(p):
""" bexpr : PEEK bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), 'PEEK',
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
type_=TYPE.ubyte) | python | def p_expr_peek(p):
""" bexpr : PEEK bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), 'PEEK',
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
type_=TYPE.ubyte) | bexpr : PEEK bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3074-L3079 |
boriel/zxbasic | zxbparser.py | p_expr_peektype_ | def p_expr_peektype_(p):
""" bexpr : PEEK LP numbertype COMMA expr RP
"""
p[0] = make_builtin(p.lineno(1), 'PEEK',
make_typecast(TYPE.uinteger, p[5], p.lineno(4)),
type_=p[3]) | python | def p_expr_peektype_(p):
""" bexpr : PEEK LP numbertype COMMA expr RP
"""
p[0] = make_builtin(p.lineno(1), 'PEEK',
make_typecast(TYPE.uinteger, p[5], p.lineno(4)),
type_=p[3]) | bexpr : PEEK LP numbertype COMMA expr RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3082-L3087 |
boriel/zxbasic | zxbparser.py | p_expr_lbound | def p_expr_lbound(p):
""" bexpr : LBOUND LP ARRAY_ID RP
| UBOUND LP ARRAY_ID RP
"""
entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3))
if entry is None:
p[0] = None
return
entry.accessed = True
if p[1] == 'LBOUND':
p[0] = make_number(entry.bounds[OPTIONS.array_base.value].lower,
p.lineno(3), TYPE.uinteger)
else:
p[0] = make_number(entry.bounds[OPTIONS.array_base.value].upper,
p.lineno(3), TYPE.uinteger) | python | def p_expr_lbound(p):
""" bexpr : LBOUND LP ARRAY_ID RP
| UBOUND LP ARRAY_ID RP
"""
entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3))
if entry is None:
p[0] = None
return
entry.accessed = True
if p[1] == 'LBOUND':
p[0] = make_number(entry.bounds[OPTIONS.array_base.value].lower,
p.lineno(3), TYPE.uinteger)
else:
p[0] = make_number(entry.bounds[OPTIONS.array_base.value].upper,
p.lineno(3), TYPE.uinteger) | bexpr : LBOUND LP ARRAY_ID RP
| UBOUND LP ARRAY_ID RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3098-L3114 |
boriel/zxbasic | zxbparser.py | p_expr_lbound_expr | def p_expr_lbound_expr(p):
""" bexpr : LBOUND LP ARRAY_ID COMMA expr RP
| UBOUND LP ARRAY_ID COMMA expr RP
"""
entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3))
if entry is None:
p[0] = None
return
entry.accessed = True
num = make_typecast(TYPE.uinteger, p[5], p.lineno(6))
if is_number(num):
if num.value == 0: # 0 => Number of dims
p[0] = make_number(len(entry.bounds), p.lineno(3), TYPE.uinteger)
return
val = num.value - 1
if val < 0 or val >= len(entry.bounds):
syntax_error(p.lineno(6), "Dimension out of range")
p[0] = None
return
if p[1] == 'LBOUND':
p[0] = make_number(entry.bounds[val].lower, p.lineno(3), TYPE.uinteger)
else:
p[0] = make_number(entry.bounds[val].upper, p.lineno(3), TYPE.uinteger)
return
if p[1] == 'LBOUND':
entry.lbound_used = True
else:
entry.ubound_used = True
p[0] = make_builtin(p.lineno(1), p[1], [entry, num], type_=TYPE.uinteger) | python | def p_expr_lbound_expr(p):
""" bexpr : LBOUND LP ARRAY_ID COMMA expr RP
| UBOUND LP ARRAY_ID COMMA expr RP
"""
entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3))
if entry is None:
p[0] = None
return
entry.accessed = True
num = make_typecast(TYPE.uinteger, p[5], p.lineno(6))
if is_number(num):
if num.value == 0: # 0 => Number of dims
p[0] = make_number(len(entry.bounds), p.lineno(3), TYPE.uinteger)
return
val = num.value - 1
if val < 0 or val >= len(entry.bounds):
syntax_error(p.lineno(6), "Dimension out of range")
p[0] = None
return
if p[1] == 'LBOUND':
p[0] = make_number(entry.bounds[val].lower, p.lineno(3), TYPE.uinteger)
else:
p[0] = make_number(entry.bounds[val].upper, p.lineno(3), TYPE.uinteger)
return
if p[1] == 'LBOUND':
entry.lbound_used = True
else:
entry.ubound_used = True
p[0] = make_builtin(p.lineno(1), p[1], [entry, num], type_=TYPE.uinteger) | bexpr : LBOUND LP ARRAY_ID COMMA expr RP
| UBOUND LP ARRAY_ID COMMA expr RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3117-L3151 |
boriel/zxbasic | zxbparser.py | p_len | def p_len(p):
""" bexpr : LEN bexpr %prec UMINUS
"""
arg = p[2]
if arg is None:
p[0] = None
elif isinstance(arg, symbols.VAR) and arg.class_ == CLASS.array:
p[0] = make_number(len(arg.bounds), lineno=p.lineno(1)) # Do constant folding
elif arg.type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(arg.type_))
p[0] = None
elif is_string(arg): # Constant string?
p[0] = make_number(len(arg.value), lineno=p.lineno(1)) # Do constant folding
else:
p[0] = make_builtin(p.lineno(1), 'LEN', arg, type_=TYPE.uinteger) | python | def p_len(p):
""" bexpr : LEN bexpr %prec UMINUS
"""
arg = p[2]
if arg is None:
p[0] = None
elif isinstance(arg, symbols.VAR) and arg.class_ == CLASS.array:
p[0] = make_number(len(arg.bounds), lineno=p.lineno(1)) # Do constant folding
elif arg.type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(arg.type_))
p[0] = None
elif is_string(arg): # Constant string?
p[0] = make_number(len(arg.value), lineno=p.lineno(1)) # Do constant folding
else:
p[0] = make_builtin(p.lineno(1), 'LEN', arg, type_=TYPE.uinteger) | bexpr : LEN bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3154-L3168 |
boriel/zxbasic | zxbparser.py | p_sizeof | def p_sizeof(p):
""" bexpr : SIZEOF LP type RP
| SIZEOF LP ID RP
| SIZEOF LP ARRAY_ID RP
"""
if TYPE.to_type(p[3].lower()) is not None:
p[0] = make_number(TYPE.size(TYPE.to_type(p[3].lower())),
lineno=p.lineno(3))
else:
entry = SYMBOL_TABLE.get_id_or_make_var(p[3], p.lineno(1))
p[0] = make_number(TYPE.size(entry.type_), lineno=p.lineno(3)) | python | def p_sizeof(p):
""" bexpr : SIZEOF LP type RP
| SIZEOF LP ID RP
| SIZEOF LP ARRAY_ID RP
"""
if TYPE.to_type(p[3].lower()) is not None:
p[0] = make_number(TYPE.size(TYPE.to_type(p[3].lower())),
lineno=p.lineno(3))
else:
entry = SYMBOL_TABLE.get_id_or_make_var(p[3], p.lineno(1))
p[0] = make_number(TYPE.size(entry.type_), lineno=p.lineno(3)) | bexpr : SIZEOF LP type RP
| SIZEOF LP ID RP
| SIZEOF LP ARRAY_ID RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3171-L3181 |
boriel/zxbasic | zxbparser.py | p_str | def p_str(p):
""" string : STR expr %prec UMINUS
"""
if is_number(p[2]): # A constant is converted to string directly
p[0] = symbols.STRING(str(p[2].value), p.lineno(1))
else:
p[0] = make_builtin(p.lineno(1), 'STR',
make_typecast(TYPE.float_, p[2], p.lineno(1)),
type_=TYPE.string) | python | def p_str(p):
""" string : STR expr %prec UMINUS
"""
if is_number(p[2]): # A constant is converted to string directly
p[0] = symbols.STRING(str(p[2].value), p.lineno(1))
else:
p[0] = make_builtin(p.lineno(1), 'STR',
make_typecast(TYPE.float_, p[2], p.lineno(1)),
type_=TYPE.string) | string : STR expr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3184-L3192 |
boriel/zxbasic | zxbparser.py | p_chr_one | def p_chr_one(p):
""" string : CHR bexpr %prec UMINUS
"""
arg_list = make_arg_list(make_argument(p[2], p.lineno(1)))
arg_list[0].value = make_typecast(TYPE.ubyte, arg_list[0].value, p.lineno(1))
p[0] = make_builtin(p.lineno(1), 'CHR', arg_list, type_=TYPE.string) | python | def p_chr_one(p):
""" string : CHR bexpr %prec UMINUS
"""
arg_list = make_arg_list(make_argument(p[2], p.lineno(1)))
arg_list[0].value = make_typecast(TYPE.ubyte, arg_list[0].value, p.lineno(1))
p[0] = make_builtin(p.lineno(1), 'CHR', arg_list, type_=TYPE.string) | string : CHR bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3201-L3206 |
boriel/zxbasic | zxbparser.py | p_chr | def p_chr(p):
""" string : CHR arg_list
"""
if len(p[2]) < 1:
syntax_error(p.lineno(1), "CHR$ function need at less 1 parameter")
p[0] = None
return
for i in range(len(p[2])): # Convert every argument to 8bit unsigned
p[2][i].value = make_typecast(TYPE.ubyte, p[2][i].value, p.lineno(1))
p[0] = make_builtin(p.lineno(1), 'CHR', p[2], type_=TYPE.string) | python | def p_chr(p):
""" string : CHR arg_list
"""
if len(p[2]) < 1:
syntax_error(p.lineno(1), "CHR$ function need at less 1 parameter")
p[0] = None
return
for i in range(len(p[2])): # Convert every argument to 8bit unsigned
p[2][i].value = make_typecast(TYPE.ubyte, p[2][i].value, p.lineno(1))
p[0] = make_builtin(p.lineno(1), 'CHR', p[2], type_=TYPE.string) | string : CHR arg_list | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3209-L3220 |
boriel/zxbasic | zxbparser.py | p_val | def p_val(p):
""" bexpr : VAL bexpr %prec UMINUS
"""
def val(s):
try:
x = float(s)
except:
x = 0
warning(p.lineno(1), "Invalid string numeric constant '%s' evaluated as 0" % s)
return x
if p[2].type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(p[2].type_))
p[0] = None
else:
p[0] = make_builtin(p.lineno(1), 'VAL', p[2], lambda x: val(x), type_=TYPE.float_) | python | def p_val(p):
""" bexpr : VAL bexpr %prec UMINUS
"""
def val(s):
try:
x = float(s)
except:
x = 0
warning(p.lineno(1), "Invalid string numeric constant '%s' evaluated as 0" % s)
return x
if p[2].type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(p[2].type_))
p[0] = None
else:
p[0] = make_builtin(p.lineno(1), 'VAL', p[2], lambda x: val(x), type_=TYPE.float_) | bexpr : VAL bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3223-L3239 |
boriel/zxbasic | zxbparser.py | p_code | def p_code(p):
""" bexpr : CODE bexpr %prec UMINUS
"""
def asc(x):
if len(x):
return ord(x[0])
return 0
if p[2] is None:
p[0] = None
return
if p[2].type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(p[2].type_))
p[0] = None
else:
p[0] = make_builtin(p.lineno(1), 'CODE', p[2], lambda x: asc(x), type_=TYPE.ubyte) | python | def p_code(p):
""" bexpr : CODE bexpr %prec UMINUS
"""
def asc(x):
if len(x):
return ord(x[0])
return 0
if p[2] is None:
p[0] = None
return
if p[2].type_ != TYPE.string:
api.errmsg.syntax_error_expected_string(p.lineno(1), TYPE.to_string(p[2].type_))
p[0] = None
else:
p[0] = make_builtin(p.lineno(1), 'CODE', p[2], lambda x: asc(x), type_=TYPE.ubyte) | bexpr : CODE bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3242-L3260 |
boriel/zxbasic | zxbparser.py | p_sgn | def p_sgn(p):
""" bexpr : SGN bexpr %prec UMINUS
"""
sgn = lambda x: x < 0 and -1 or x > 0 and 1 or 0 # noqa
if p[2].type_ == TYPE.string:
syntax_error(p.lineno(1), "Expected a numeric expression, got TYPE.string instead")
p[0] = None
else:
if is_unsigned(p[2]) and not is_number(p[2]):
warning(p.lineno(1), "Sign of unsigned value is always 0 or 1")
p[0] = make_builtin(p.lineno(1), 'SGN', p[2], lambda x: sgn(x), type_=TYPE.byte_) | python | def p_sgn(p):
""" bexpr : SGN bexpr %prec UMINUS
"""
sgn = lambda x: x < 0 and -1 or x > 0 and 1 or 0 # noqa
if p[2].type_ == TYPE.string:
syntax_error(p.lineno(1), "Expected a numeric expression, got TYPE.string instead")
p[0] = None
else:
if is_unsigned(p[2]) and not is_number(p[2]):
warning(p.lineno(1), "Sign of unsigned value is always 0 or 1")
p[0] = make_builtin(p.lineno(1), 'SGN', p[2], lambda x: sgn(x), type_=TYPE.byte_) | bexpr : SGN bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3263-L3275 |
boriel/zxbasic | zxbparser.py | p_expr_trig | def p_expr_trig(p):
""" bexpr : math_fn bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), p[1],
make_typecast(TYPE.float_, p[2], p.lineno(1)),
{'SIN': math.sin,
'COS': math.cos,
'TAN': math.tan,
'ASN': math.asin,
'ACS': math.acos,
'ATN': math.atan,
'LN': lambda y: math.log(y, math.exp(1)), # LN(x)
'EXP': math.exp,
'SQR': math.sqrt
}[p[1]]) | python | def p_expr_trig(p):
""" bexpr : math_fn bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), p[1],
make_typecast(TYPE.float_, p[2], p.lineno(1)),
{'SIN': math.sin,
'COS': math.cos,
'TAN': math.tan,
'ASN': math.asin,
'ACS': math.acos,
'ATN': math.atan,
'LN': lambda y: math.log(y, math.exp(1)), # LN(x)
'EXP': math.exp,
'SQR': math.sqrt
}[p[1]]) | bexpr : math_fn bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3281-L3295 |
boriel/zxbasic | zxbparser.py | p_abs | def p_abs(p):
""" bexpr : ABS bexpr %prec UMINUS
"""
if is_unsigned(p[2]):
p[0] = p[2]
warning(p.lineno(1), "Redundant operation ABS for unsigned value")
return
p[0] = make_builtin(p.lineno(1), 'ABS', p[2], lambda x: x if x >= 0 else -x) | python | def p_abs(p):
""" bexpr : ABS bexpr %prec UMINUS
"""
if is_unsigned(p[2]):
p[0] = p[2]
warning(p.lineno(1), "Redundant operation ABS for unsigned value")
return
p[0] = make_builtin(p.lineno(1), 'ABS', p[2], lambda x: x if x >= 0 else -x) | bexpr : ABS bexpr %prec UMINUS | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L3321-L3329 |
boriel/zxbasic | symbols/bound.py | SymbolBOUND.make_node | def make_node(lower, upper, lineno):
""" Creates an array bound
"""
if not is_static(lower, upper):
syntax_error(lineno, 'Array bounds must be constants')
return None
if isinstance(lower, SymbolVAR):
lower = lower.value
if isinstance(upper, SymbolVAR):
upper = upper.value
lower.value = int(lower.value)
upper.value = int(upper.value)
if lower.value < 0:
syntax_error(lineno, 'Array bounds must be greater than 0')
return None
if lower.value > upper.value:
syntax_error(lineno, 'Lower array bound must be less or equal to upper one')
return None
return SymbolBOUND(lower.value, upper.value) | python | def make_node(lower, upper, lineno):
""" Creates an array bound
"""
if not is_static(lower, upper):
syntax_error(lineno, 'Array bounds must be constants')
return None
if isinstance(lower, SymbolVAR):
lower = lower.value
if isinstance(upper, SymbolVAR):
upper = upper.value
lower.value = int(lower.value)
upper.value = int(upper.value)
if lower.value < 0:
syntax_error(lineno, 'Array bounds must be greater than 0')
return None
if lower.value > upper.value:
syntax_error(lineno, 'Lower array bound must be less or equal to upper one')
return None
return SymbolBOUND(lower.value, upper.value) | Creates an array bound | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/bound.py#L44-L67 |
boriel/zxbasic | basic.py | Basic.number | def number(self, number):
""" Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535)
"""
s = [ord(x) for x in str(number)] + [14] # Bytes of string representation in bytes
if number == int(number) and abs(number) < 65536: # integer form?
sign = 0xFF if number < 0 else 0
b = [0, sign] + self.numberLH(number) + [0]
else: # Float form
(C, ED, LH) = fp.immediate_float(number)
C = C[:2] # Remove 'h'
ED = ED[:4] # Remove 'h'
LH = LH[:4] # Remove 'h'
b = [int(C, 16)] # Convert to BASE 10
b += [int(ED[:2], 16), int(ED[2:], 16)]
b += [int(LH[:2], 16), int(LH[2:], 16)]
return s + b | python | def number(self, number):
""" Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535)
"""
s = [ord(x) for x in str(number)] + [14] # Bytes of string representation in bytes
if number == int(number) and abs(number) < 65536: # integer form?
sign = 0xFF if number < 0 else 0
b = [0, sign] + self.numberLH(number) + [0]
else: # Float form
(C, ED, LH) = fp.immediate_float(number)
C = C[:2] # Remove 'h'
ED = ED[:4] # Remove 'h'
LH = LH[:4] # Remove 'h'
b = [int(C, 16)] # Convert to BASE 10
b += [int(ED[:2], 16), int(ED[2:], 16)]
b += [int(LH[:2], 16), int(LH[2:], 16)]
return s + b | Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L79-L99 |
boriel/zxbasic | basic.py | Basic.parse_sentence | def parse_sentence(self, string):
""" Parses the given sentence. BASIC commands must be
types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc...
"""
result = []
def shift(string_):
""" Returns first word of a string, and remaining
"""
string_ = string_.strip() # Remove spaces and tabs
if not string_: # Avoid empty strings
return '', ''
i = string_.find(' ')
if i == -1:
command_ = string_
string_ = ''
else:
command_ = string_[:i]
string_ = string_[i:]
return command_, string_
command, string = shift(string)
while command != '':
result += self.token(command) | python | def parse_sentence(self, string):
""" Parses the given sentence. BASIC commands must be
types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc...
"""
result = []
def shift(string_):
""" Returns first word of a string, and remaining
"""
string_ = string_.strip() # Remove spaces and tabs
if not string_: # Avoid empty strings
return '', ''
i = string_.find(' ')
if i == -1:
command_ = string_
string_ = ''
else:
command_ = string_[:i]
string_ = string_[i:]
return command_, string_
command, string = shift(string)
while command != '':
result += self.token(command) | Parses the given sentence. BASIC commands must be
types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc... | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L114-L141 |
boriel/zxbasic | basic.py | Basic.sentence_bytes | def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
if isinstance(i, str):
result.extend(self.literal(i))
elif isinstance(i, float) or isinstance(i, int): # A number?
result.extend(self.number(i))
else:
result.extend(i) # Must be another thing
return result | python | def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
if isinstance(i, str):
result.extend(self.literal(i))
elif isinstance(i, float) or isinstance(i, int): # A number?
result.extend(self.number(i))
else:
result.extend(i) # Must be another thing
return result | Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L143-L158 |
boriel/zxbasic | basic.py | Basic.line | def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10
self.current_line = line_number
sep = []
result = []
for sentence in sentences:
result.extend(sep)
result.extend(self.sentence_bytes(sentence))
sep = [ord(':')]
result.extend([ENTER])
result = self.line_number(line_number) + self.numberLH(len(result)) + result
return result | python | def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10
self.current_line = line_number
sep = []
result = []
for sentence in sentences:
result.extend(sep)
result.extend(self.sentence_bytes(sentence))
sep = [ord(':')]
result.extend([ENTER])
result = self.line_number(line_number) + self.numberLH(len(result)) + result
return result | Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L160-L179 |
boriel/zxbasic | basic.py | Basic.add_line | def add_line(self, sentences, line_number=None):
""" Add current line to the output.
See self.line() for more info
"""
self.bytes += self.line(sentences, line_number) | python | def add_line(self, sentences, line_number=None):
""" Add current line to the output.
See self.line() for more info
"""
self.bytes += self.line(sentences, line_number) | Add current line to the output.
See self.line() for more info | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L181-L185 |
boriel/zxbasic | symbols/arrayaccess.py | SymbolARRAYACCESS.offset | def offset(self):
""" If this is a constant access (e.g. A(1))
return the offset in bytes from the beginning of the
variable in memory.
Otherwise, if it's not constant (e.g. A(i))
returns None
"""
offset = 0
# Now we must typecast each argument to a u16 (POINTER) type
# i is the dimension ith index, b is the bound
for i, b in zip(self.arglist, self.entry.bounds):
tmp = i.children[0]
if is_number(tmp) or is_const(tmp):
if offset is not None:
offset = offset * b.count + tmp.value
else:
offset = None
break
if offset is not None:
offset = TYPE.size(gl.SIZE_TYPE) + TYPE.size(gl.BOUND_TYPE) * len(self.arglist) + offset * self.type_.size
return offset | python | def offset(self):
""" If this is a constant access (e.g. A(1))
return the offset in bytes from the beginning of the
variable in memory.
Otherwise, if it's not constant (e.g. A(i))
returns None
"""
offset = 0
# Now we must typecast each argument to a u16 (POINTER) type
# i is the dimension ith index, b is the bound
for i, b in zip(self.arglist, self.entry.bounds):
tmp = i.children[0]
if is_number(tmp) or is_const(tmp):
if offset is not None:
offset = offset * b.count + tmp.value
else:
offset = None
break
if offset is not None:
offset = TYPE.size(gl.SIZE_TYPE) + TYPE.size(gl.BOUND_TYPE) * len(self.arglist) + offset * self.type_.size
return offset | If this is a constant access (e.g. A(1))
return the offset in bytes from the beginning of the
variable in memory.
Otherwise, if it's not constant (e.g. A(i))
returns None | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/arrayaccess.py#L73-L96 |
boriel/zxbasic | symbols/arrayaccess.py | SymbolARRAYACCESS.make_node | def make_node(cls, id_, arglist, lineno):
""" Creates an array access. A(x1, x2, ..., xn)
"""
assert isinstance(arglist, SymbolARGLIST)
variable = gl.SYMBOL_TABLE.access_array(id_, lineno)
if variable is None:
return None
if len(variable.bounds) != len(arglist):
syntax_error(lineno, "Array '%s' has %i dimensions, not %i" %
(variable.name, len(variable.bounds), len(arglist)))
return None
# Checks for array subscript range if the subscript is constant
# e.g. A(1) is a constant subscript access
for i, b in zip(arglist, variable.bounds):
btype = gl.SYMBOL_TABLE.basic_types[gl.BOUND_TYPE]
lower_bound = NUMBER(b.lower, type_=btype, lineno=lineno)
i.value = BINARY.make_node('MINUS',
TYPECAST.make_node(btype, i.value, lineno),
lower_bound, lineno, func=lambda x, y: x - y,
type_=btype)
if is_number(i.value) or is_const(i.value):
val = i.value.value
if val < 0 or val > b.count:
warning(lineno, "Array '%s' subscript out of range" % id_)
# Returns the variable entry and the node
return cls(variable, arglist, lineno) | python | def make_node(cls, id_, arglist, lineno):
""" Creates an array access. A(x1, x2, ..., xn)
"""
assert isinstance(arglist, SymbolARGLIST)
variable = gl.SYMBOL_TABLE.access_array(id_, lineno)
if variable is None:
return None
if len(variable.bounds) != len(arglist):
syntax_error(lineno, "Array '%s' has %i dimensions, not %i" %
(variable.name, len(variable.bounds), len(arglist)))
return None
# Checks for array subscript range if the subscript is constant
# e.g. A(1) is a constant subscript access
for i, b in zip(arglist, variable.bounds):
btype = gl.SYMBOL_TABLE.basic_types[gl.BOUND_TYPE]
lower_bound = NUMBER(b.lower, type_=btype, lineno=lineno)
i.value = BINARY.make_node('MINUS',
TYPECAST.make_node(btype, i.value, lineno),
lower_bound, lineno, func=lambda x, y: x - y,
type_=btype)
if is_number(i.value) or is_const(i.value):
val = i.value.value
if val < 0 or val > b.count:
warning(lineno, "Array '%s' subscript out of range" % id_)
# Returns the variable entry and the node
return cls(variable, arglist, lineno) | Creates an array access. A(x1, x2, ..., xn) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/arrayaccess.py#L99-L127 |
boriel/zxbasic | zxbasmpplex.py | Lexer.t_INITIAL_COMMENT | def t_INITIAL_COMMENT(self, t):
r';'
t.lexer.push_state('asmcomment')
t.type = 'TOKEN'
t.value = ';'
return t | python | def t_INITIAL_COMMENT(self, t):
r';'
t.lexer.push_state('asmcomment')
t.type = 'TOKEN'
t.value = ';'
return t | r'; | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L74-L79 |
boriel/zxbasic | zxbasmpplex.py | Lexer.t_prepro_define_defargs_defargsopt_defexpr_pragma_NEWLINE | def t_prepro_define_defargs_defargsopt_defexpr_pragma_NEWLINE(self, t):
r'\r?\n'
t.lexer.lineno += 1
t.lexer.pop_state()
return t | python | def t_prepro_define_defargs_defargsopt_defexpr_pragma_NEWLINE(self, t):
r'\r?\n'
t.lexer.lineno += 1
t.lexer.pop_state()
return t | r'\r?\n | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L111-L115 |
boriel/zxbasic | zxbasmpplex.py | Lexer.t_prepro_define_pragma_defargs_defargsopt_CONTINUE | def t_prepro_define_pragma_defargs_defargsopt_CONTINUE(self, t):
r'[_\\]\r?\n'
t.lexer.lineno += 1
t.value = t.value[1:]
t.type = 'NEWLINE'
return t | python | def t_prepro_define_pragma_defargs_defargsopt_CONTINUE(self, t):
r'[_\\]\r?\n'
t.lexer.lineno += 1
t.value = t.value[1:]
t.type = 'NEWLINE'
return t | r'[_\\]\r?\n | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L127-L132 |
boriel/zxbasic | zxbasmpplex.py | Lexer.t_prepro_ID | def t_prepro_ID(self, t):
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = reserved_directives.get(t.value.lower(), 'ID')
if t.type == 'DEFINE':
t.lexer.begin('define')
elif t.type == 'PRAGMA':
t.lexer.begin('pragma')
return t | python | def t_prepro_ID(self, t):
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = reserved_directives.get(t.value.lower(), 'ID')
if t.type == 'DEFINE':
t.lexer.begin('define')
elif t.type == 'PRAGMA':
t.lexer.begin('pragma')
return t | r'[_a-zA-Z][_a-zA-Z0-9]* | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L149-L156 |
boriel/zxbasic | zxbasmpplex.py | Lexer.t_INIIAL_sharp | def t_INIIAL_sharp(self, t):
r'\#' # Only matches if at beginning of line and "#"
if t.value == '#' and self.find_column(t) == 1:
t.lexer.push_state('prepro') | python | def t_INIIAL_sharp(self, t):
r'\#' # Only matches if at beginning of line and "#"
if t.value == '#' and self.find_column(t) == 1:
t.lexer.push_state('prepro') | r'\# | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L249-L252 |
boriel/zxbasic | zxbasmpplex.py | Lexer.put_current_line | def put_current_line(self, prefix=''):
""" Returns line and file for include / end of include sequences.
"""
return '%s#line %i "%s"\n' % (prefix, self.lex.lineno, os.path.basename(self.filestack[-1][0])) | python | def put_current_line(self, prefix=''):
""" Returns line and file for include / end of include sequences.
"""
return '%s#line %i "%s"\n' % (prefix, self.lex.lineno, os.path.basename(self.filestack[-1][0])) | Returns line and file for include / end of include sequences. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L295-L298 |
boriel/zxbasic | zxbasmpplex.py | Lexer.include | def include(self, filename):
""" Changes FILENAME and line count
"""
if filename != STDIN and filename in [x[0] for x in self.filestack]: # Already included?
self.warning(' Recursive inclusion')
self.filestack.append([filename, 1, self.lex, self.input_data])
self.lex = lex.lex(object=self)
result = self.put_current_line() # First #line start with \n (EOL)
try:
if filename == STDIN:
self.input_data = sys.stdin.read()
else:
self.input_data = api.utils.read_txt_file(filename)
if len(self.input_data) and self.input_data[-1] != EOL:
self.input_data += EOL
except IOError:
self.input_data = EOL
self.lex.input(self.input_data)
return result | python | def include(self, filename):
""" Changes FILENAME and line count
"""
if filename != STDIN and filename in [x[0] for x in self.filestack]: # Already included?
self.warning(' Recursive inclusion')
self.filestack.append([filename, 1, self.lex, self.input_data])
self.lex = lex.lex(object=self)
result = self.put_current_line() # First #line start with \n (EOL)
try:
if filename == STDIN:
self.input_data = sys.stdin.read()
else:
self.input_data = api.utils.read_txt_file(filename)
if len(self.input_data) and self.input_data[-1] != EOL:
self.input_data += EOL
except IOError:
self.input_data = EOL
self.lex.input(self.input_data)
return result | Changes FILENAME and line count | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L300-L322 |
boriel/zxbasic | symbols/var.py | SymbolVAR.add_alias | def add_alias(self, entry):
""" Adds id to the current list 'aliased_by'
"""
assert isinstance(entry, SymbolVAR)
self.aliased_by.append(entry) | python | def add_alias(self, entry):
""" Adds id to the current list 'aliased_by'
"""
assert isinstance(entry, SymbolVAR)
self.aliased_by.append(entry) | Adds id to the current list 'aliased_by' | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/var.py#L78-L82 |
boriel/zxbasic | symbols/var.py | SymbolVAR.make_alias | def make_alias(self, entry):
""" Make this variable an alias of another one
"""
entry.add_alias(self)
self.alias = entry
self.scope = entry.scope # Local aliases can be "global" (static)
self.byref = entry.byref
self.offset = entry.offset
self.addr = entry.addr | python | def make_alias(self, entry):
""" Make this variable an alias of another one
"""
entry.add_alias(self)
self.alias = entry
self.scope = entry.scope # Local aliases can be "global" (static)
self.byref = entry.byref
self.offset = entry.offset
self.addr = entry.addr | Make this variable an alias of another one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/var.py#L84-L92 |
boriel/zxbasic | symbols/var.py | SymbolVAR.to_label | def to_label(var_instance):
""" Converts a var_instance to a label one
"""
# This can be done 'cause LABEL is just a dummy descent of VAR
assert isinstance(var_instance, SymbolVAR)
from symbols import LABEL
var_instance.__class__ = LABEL
var_instance.class_ = CLASS.label
var_instance._scope_owner = []
return var_instance | python | def to_label(var_instance):
""" Converts a var_instance to a label one
"""
# This can be done 'cause LABEL is just a dummy descent of VAR
assert isinstance(var_instance, SymbolVAR)
from symbols import LABEL
var_instance.__class__ = LABEL
var_instance.class_ = CLASS.label
var_instance._scope_owner = []
return var_instance | Converts a var_instance to a label one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/var.py#L130-L139 |
boriel/zxbasic | symbols/var.py | SymbolVAR.to_function | def to_function(var_instance, lineno=None):
""" Converts a var_instance to a function one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance | python | def to_function(var_instance, lineno=None):
""" Converts a var_instance to a function one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance | Converts a var_instance to a function one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/var.py#L142-L150 |
boriel/zxbasic | symbols/var.py | SymbolVAR.to_vararray | def to_vararray(var_instance, bounds):
""" Converts a var_instance to a var array one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import BOUNDLIST
from symbols import VARARRAY
assert isinstance(bounds, BOUNDLIST)
var_instance.__class__ = VARARRAY
var_instance.class_ = CLASS.array
var_instance.bounds = bounds
return var_instance | python | def to_vararray(var_instance, bounds):
""" Converts a var_instance to a var array one
"""
assert isinstance(var_instance, SymbolVAR)
from symbols import BOUNDLIST
from symbols import VARARRAY
assert isinstance(bounds, BOUNDLIST)
var_instance.__class__ = VARARRAY
var_instance.class_ = CLASS.array
var_instance.bounds = bounds
return var_instance | Converts a var_instance to a var array one | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/var.py#L153-L163 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _paddr | def _paddr(ins):
""" Returns code sequence which points to
local variable or parameter (HL)
"""
output = []
oper = ins.quad[1]
indirect = (oper[0] == '*')
if indirect:
oper = oper[1:]
I = int(oper)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, e')
output.append('push hl')
return output | python | def _paddr(ins):
""" Returns code sequence which points to
local variable or parameter (HL)
"""
output = []
oper = ins.quad[1]
indirect = (oper[0] == '*')
if indirect:
oper = oper[1:]
I = int(oper)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, e')
output.append('push hl')
return output | Returns code sequence which points to
local variable or parameter (HL) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L22-L49 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pload | def _pload(offset, size):
""" Generic parameter loading.
Emmits output code for setting IX at the right location.
size = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
"""
output = []
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0: # If it is a parameter, round up to even bytes
I += 4 + (size % 2 if not indirect else 0) # Return Address + "push IX"
ix_changed = (indirect or size < 5) and (abs(I) + size) > 127 # Offset > 127 bytes. Need to change IX
if ix_changed: # more than 1 byte
output.append('push ix')
output.append('ld de, %i' % I)
output.append('add ix, de')
I = 0
elif size == 5: # For floating point numbers we always use DE as IX offset
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
I = 0
if indirect:
output.append('ld h, (ix%+i)' % (I + 1))
output.append('ld l, (ix%+i)' % I)
if size == 1:
output.append('ld a, (hl)')
elif size == 2:
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
elif size == 4:
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
else: # Floating point
output.append('call __ILOADF')
REQUIRES.add('iloadf.asm')
else:
if size == 1:
output.append('ld a, (ix%+i)' % I)
else:
if size <= 4: # 16/32bit integer, low part
output.append('ld l, (ix%+i)' % I)
output.append('ld h, (ix%+i)' % (I + 1))
if size > 2: # 32 bit integer, high part
output.append('ld e, (ix%+i)' % (I + 2))
output.append('ld d, (ix%+i)' % (I + 3))
else: # Floating point
output.append('call __PLOADF')
REQUIRES.add('ploadf.asm')
if ix_changed:
output.append('pop ix')
return output | python | def _pload(offset, size):
""" Generic parameter loading.
Emmits output code for setting IX at the right location.
size = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
"""
output = []
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0: # If it is a parameter, round up to even bytes
I += 4 + (size % 2 if not indirect else 0) # Return Address + "push IX"
ix_changed = (indirect or size < 5) and (abs(I) + size) > 127 # Offset > 127 bytes. Need to change IX
if ix_changed: # more than 1 byte
output.append('push ix')
output.append('ld de, %i' % I)
output.append('add ix, de')
I = 0
elif size == 5: # For floating point numbers we always use DE as IX offset
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
I = 0
if indirect:
output.append('ld h, (ix%+i)' % (I + 1))
output.append('ld l, (ix%+i)' % I)
if size == 1:
output.append('ld a, (hl)')
elif size == 2:
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
elif size == 4:
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
else: # Floating point
output.append('call __ILOADF')
REQUIRES.add('iloadf.asm')
else:
if size == 1:
output.append('ld a, (ix%+i)' % I)
else:
if size <= 4: # 16/32bit integer, low part
output.append('ld l, (ix%+i)' % I)
output.append('ld h, (ix%+i)' % (I + 1))
if size > 2: # 32 bit integer, high part
output.append('ld e, (ix%+i)' % (I + 2))
output.append('ld d, (ix%+i)' % (I + 3))
else: # Floating point
output.append('call __PLOADF')
REQUIRES.add('ploadf.asm')
if ix_changed:
output.append('pop ix')
return output | Generic parameter loading.
Emmits output code for setting IX at the right location.
size = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L52-L120 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pload32 | def _pload32(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
"""
output = _pload(ins.quad[2], 4)
output.append('push de')
output.append('push hl')
return output | python | def _pload32(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
"""
output = _pload(ins.quad[2], 4)
output.append('push de')
output.append('push hl')
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L148-L158 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _ploadf | def _ploadf(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
"""
output = _pload(ins.quad[2], 5)
output.extend(_fpush())
return output | python | def _ploadf(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
"""
output = _pload(ins.quad[2], 5)
output.extend(_fpush())
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L161-L169 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _ploadstr | def _ploadstr(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
"""
output = _pload(ins.quad[2], 2)
if ins.quad[1][0] != '$':
output.append('call __LOADSTR')
REQUIRES.add('loadstr.asm')
output.append('push hl')
return output | python | def _ploadstr(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
"""
output = _pload(ins.quad[2], 2)
if ins.quad[1][0] != '$':
output.append('call __LOADSTR')
REQUIRES.add('loadstr.asm')
output.append('push hl')
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L172-L185 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _fploadstr | def _fploadstr(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
Unlike ploadstr, this version does not push the result
back into the stack.
"""
output = _pload(ins.quad[2], 2)
if ins.quad[1][0] != '$':
output.append('call __LOADSTR')
REQUIRES.add('loadstr.asm')
return output | python | def _fploadstr(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
Unlike ploadstr, this version does not push the result
back into the stack.
"""
output = _pload(ins.quad[2], 2)
if ins.quad[1][0] != '$':
output.append('call __LOADSTR')
REQUIRES.add('loadstr.asm')
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
Unlike ploadstr, this version does not push the result
back into the stack. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L188-L201 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstore8 | def _pstore8(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
size = 0
if indirect:
offset = offset[1:]
size = 1
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
if not indirect:
I += 1 # F flag ignored
if is_int(value):
output = []
else:
output = _8bit_oper(value)
ix_changed = not (-128 + size <= I <= 127 - size) # Offset > 127 bytes. Need to change IX
if ix_changed: # more than 1 byte
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
if ix_changed:
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
else:
output.append('ld h, (ix%+i)' % (I + 1))
output.append('ld l, (ix%+i)' % I)
if is_int(value):
output.append('ld (hl), %i' % int8(value))
else:
output.append('ld (hl), a')
return output
# direct store
if ix_changed:
if is_int(value):
output.append('ld (hl), %i' % int8(value))
else:
output.append('ld (hl), a')
return output
if is_int(value):
output.append('ld (ix%+i), %i' % (I, int8(value)))
else:
output.append('ld (ix%+i), a' % I)
return output | python | def _pstore8(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
size = 0
if indirect:
offset = offset[1:]
size = 1
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
if not indirect:
I += 1 # F flag ignored
if is_int(value):
output = []
else:
output = _8bit_oper(value)
ix_changed = not (-128 + size <= I <= 127 - size) # Offset > 127 bytes. Need to change IX
if ix_changed: # more than 1 byte
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
if ix_changed:
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
else:
output.append('ld h, (ix%+i)' % (I + 1))
output.append('ld l, (ix%+i)' % I)
if is_int(value):
output.append('ld (hl), %i' % int8(value))
else:
output.append('ld (hl), a')
return output
# direct store
if ix_changed:
if is_int(value):
output.append('ld (hl), %i' % int8(value))
else:
output.append('ld (hl), a')
return output
if is_int(value):
output.append('ld (ix%+i), %i' % (I, int8(value)))
else:
output.append('ld (ix%+i), a' % I)
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L204-L267 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstore16 | def _pstore16(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
size = 1
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
if is_int(value):
output = []
else:
output = _16bit_oper(value)
ix_changed = not (-128 + size <= I <= 127 - size) # Offset > 127 bytes. Need to change IX
if indirect:
if is_int(value):
output.append('ld hl, %i' % int16(value))
output.append('ld bc, %i' % I)
output.append('call __PISTORE16')
REQUIRES.add('istore16.asm')
return output
# direct store
if ix_changed: # more than 1 byte
if not is_int(value):
output.append('ex de, hl')
output.append('push ix')
output.append('pop hl')
output.append('ld bc, %i' % I)
output.append('add hl, bc')
if is_int(value):
v = int16(value)
output.append('ld (hl), %i' % (v & 0xFF))
output.append('inc hl')
output.append('ld (hl), %i' % (v >> 8))
return output
else:
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
return output
if is_int(value):
v = int16(value)
output.append('ld (ix%+i), %i' % (I, v & 0xFF))
output.append('ld (ix%+i), %i' % (I + 1, v >> 8))
else:
output.append('ld (ix%+i), l' % I)
output.append('ld (ix%+i), h' % (I + 1))
return output | python | def _pstore16(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
size = 1
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
if is_int(value):
output = []
else:
output = _16bit_oper(value)
ix_changed = not (-128 + size <= I <= 127 - size) # Offset > 127 bytes. Need to change IX
if indirect:
if is_int(value):
output.append('ld hl, %i' % int16(value))
output.append('ld bc, %i' % I)
output.append('call __PISTORE16')
REQUIRES.add('istore16.asm')
return output
# direct store
if ix_changed: # more than 1 byte
if not is_int(value):
output.append('ex de, hl')
output.append('push ix')
output.append('pop hl')
output.append('ld bc, %i' % I)
output.append('add hl, bc')
if is_int(value):
v = int16(value)
output.append('ld (hl), %i' % (v & 0xFF))
output.append('inc hl')
output.append('ld (hl), %i' % (v >> 8))
return output
else:
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
return output
if is_int(value):
v = int16(value)
output.append('ld (ix%+i), %i' % (I, v & 0xFF))
output.append('ld (ix%+i), %i' % (I + 1, v >> 8))
else:
output.append('ld (ix%+i), l' % I)
output.append('ld (ix%+i), h' % (I + 1))
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L270-L333 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstore32 | def _pstore32(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _32bit_oper(value)
if indirect:
output.append('ld bc, %i' % I)
output.append('call __PISTORE32')
REQUIRES.add('pistore32.asm')
return output
# direct store
output.append('ld bc, %i' % I)
output.append('call __PSTORE32')
REQUIRES.add('pstore32.asm')
return output | python | def _pstore32(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _32bit_oper(value)
if indirect:
output.append('ld bc, %i' % I)
output.append('call __PISTORE32')
REQUIRES.add('pistore32.asm')
return output
# direct store
output.append('ld bc, %i' % I)
output.append('call __PSTORE32')
REQUIRES.add('pstore32.asm')
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L336-L365 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstoref16 | def _pstoref16(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _f16_oper(value)
if indirect:
output.append('ld bc, %i' % I)
output.append('call __PISTORE32')
REQUIRES.add('pistore32.asm')
return output
# direct store
output.append('ld bc, %i' % I)
output.append('call __PSTORE32')
REQUIRES.add('pstore32.asm')
return output | python | def _pstoref16(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _f16_oper(value)
if indirect:
output.append('ld bc, %i' % I)
output.append('call __PISTORE32')
REQUIRES.add('pistore32.asm')
return output
# direct store
output.append('ld bc, %i' % I)
output.append('call __PSTORE32')
REQUIRES.add('pstore32.asm')
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L368-L397 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstoref | def _pstoref(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _float_oper(value)
if indirect:
output.append('ld hl, %i' % I)
output.append('call __PISTOREF')
REQUIRES.add('storef.asm')
return output
# direct store
output.append('ld hl, %i' % I)
output.append('call __PSTOREF')
REQUIRES.add('pstoref.asm')
return output | python | def _pstoref(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output = _float_oper(value)
if indirect:
output.append('ld hl, %i' % I)
output.append('call __PISTOREF')
REQUIRES.add('storef.asm')
return output
# direct store
output.append('ld hl, %i' % I)
output.append('call __PSTOREF')
REQUIRES.add('pstoref.asm')
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L400-L429 |
boriel/zxbasic | arch/zx48k/backend/__pload.py | _pstorestr | def _pstorestr(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
Note: This procedure proceeds as _pstore16, since STRINGS are 16bit pointers.
"""
output = []
temporal = False
# 2nd operand first, because must go into the stack
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
if value[0] == '_':
output.append('ld de, (%s)' % value)
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
elif value[0] == '#':
output.append('ld de, %s' % value[1:])
else:
output.append('pop de')
temporal = value[0] != '$'
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
# Now 1st operand
value = ins.quad[1]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
I = int(value)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('ld bc, %i' % I)
if not temporal:
if indirect:
output.append('call __PISTORE_STR')
REQUIRES.add('storestr.asm')
else:
output.append('call __PSTORE_STR')
REQUIRES.add('pstorestr.asm')
else:
if indirect:
output.append('call __PISTORE_STR2')
REQUIRES.add('storestr2.asm')
else:
output.append('call __PSTORE_STR2')
REQUIRES.add('pstorestr2.asm')
return output | python | def _pstorestr(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
Note: This procedure proceeds as _pstore16, since STRINGS are 16bit pointers.
"""
output = []
temporal = False
# 2nd operand first, because must go into the stack
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
if value[0] == '_':
output.append('ld de, (%s)' % value)
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
elif value[0] == '#':
output.append('ld de, %s' % value[1:])
else:
output.append('pop de')
temporal = value[0] != '$'
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
# Now 1st operand
value = ins.quad[1]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
I = int(value)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('ld bc, %i' % I)
if not temporal:
if indirect:
output.append('call __PISTORE_STR')
REQUIRES.add('storestr.asm')
else:
output.append('call __PSTORE_STR')
REQUIRES.add('pstorestr.asm')
else:
if indirect:
output.append('call __PISTORE_STR2')
REQUIRES.add('storestr2.asm')
else:
output.append('call __PSTORE_STR2')
REQUIRES.add('pstorestr2.asm')
return output | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
Note: This procedure proceeds as _pstore16, since STRINGS are 16bit pointers. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L432-L497 |
boriel/zxbasic | symbols/unary.py | SymbolUNARY.make_node | def make_node(cls, lineno, operator, operand, func=None, type_=None):
""" Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: lambda function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string'
"""
assert type_ is None or isinstance(type_, SymbolTYPE)
if func is not None: # Try constant-folding
if is_number(operand): # e.g. ABS(-5)
return SymbolNUMBER(func(operand.value), lineno=lineno)
elif is_string(operand): # e.g. LEN("a")
return SymbolSTRING(func(operand.text), lineno=lineno)
if type_ is None:
type_ = operand.type_
if operator == 'MINUS':
if not type_.is_signed:
type_ = type_.to_signed()
operand = SymbolTYPECAST.make_node(type_, operand, lineno)
elif operator == 'NOT':
type_ = TYPE.ubyte
return cls(operator, operand, lineno, type_) | python | def make_node(cls, lineno, operator, operand, func=None, type_=None):
""" Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: lambda function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string'
"""
assert type_ is None or isinstance(type_, SymbolTYPE)
if func is not None: # Try constant-folding
if is_number(operand): # e.g. ABS(-5)
return SymbolNUMBER(func(operand.value), lineno=lineno)
elif is_string(operand): # e.g. LEN("a")
return SymbolSTRING(func(operand.text), lineno=lineno)
if type_ is None:
type_ = operand.type_
if operator == 'MINUS':
if not type_.is_signed:
type_ = type_.to_signed()
operand = SymbolTYPECAST.make_node(type_, operand, lineno)
elif operator == 'NOT':
type_ = TYPE.ubyte
return cls(operator, operand, lineno, type_) | Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: lambda function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string' | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/unary.py#L62-L89 |
boriel/zxbasic | api/constants.py | TYPE.to_signed | def to_signed(cls, type_):
""" Return signed type or equivalent
"""
if type_ in cls.unsigned:
return {TYPE.ubyte: TYPE.byte_,
TYPE.uinteger: TYPE.integer,
TYPE.ulong: TYPE.long_}[type_]
if type_ in cls.decimals or type_ in cls.signed:
return type_
return cls.unknown | python | def to_signed(cls, type_):
""" Return signed type or equivalent
"""
if type_ in cls.unsigned:
return {TYPE.ubyte: TYPE.byte_,
TYPE.uinteger: TYPE.integer,
TYPE.ulong: TYPE.long_}[type_]
if type_ in cls.decimals or type_ in cls.signed:
return type_
return cls.unknown | Return signed type or equivalent | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/constants.py#L148-L157 |
boriel/zxbasic | api/constants.py | TYPE.to_type | def to_type(cls, typename):
""" Converts a type ID to name. On error returns None
"""
NAME_TYPES = {cls.TYPE_NAMES[x]: x for x in cls.TYPE_NAMES}
return NAME_TYPES.get(typename, None) | python | def to_type(cls, typename):
""" Converts a type ID to name. On error returns None
"""
NAME_TYPES = {cls.TYPE_NAMES[x]: x for x in cls.TYPE_NAMES}
return NAME_TYPES.get(typename, None) | Converts a type ID to name. On error returns None | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/constants.py#L166-L170 |
boriel/zxbasic | arch/zx48k/backend/__f16.py | f16 | def f16(op):
""" Returns a floating point operand converted to 32 bits unsigned int.
Negative numbers are returned in 2 complement.
The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part)
"""
op = float(op)
negative = op < 0
if negative:
op = -op
DE = int(op)
HL = int((op - DE) * 2**16) & 0xFFFF
DE &= 0xFFFF
if negative: # Do C2
DE ^= 0xFFFF
HL ^= 0xFFFF
DEHL = ((DE << 16) | HL) + 1
HL = DEHL & 0xFFFF
DE = (DEHL >> 16) & 0xFFFF
return (DE, HL) | python | def f16(op):
""" Returns a floating point operand converted to 32 bits unsigned int.
Negative numbers are returned in 2 complement.
The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part)
"""
op = float(op)
negative = op < 0
if negative:
op = -op
DE = int(op)
HL = int((op - DE) * 2**16) & 0xFFFF
DE &= 0xFFFF
if negative: # Do C2
DE ^= 0xFFFF
HL ^= 0xFFFF
DEHL = ((DE << 16) | HL) + 1
HL = DEHL & 0xFFFF
DE = (DEHL >> 16) & 0xFFFF
return (DE, HL) | Returns a floating point operand converted to 32 bits unsigned int.
Negative numbers are returned in 2 complement.
The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part) | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__f16.py#L21-L45 |
boriel/zxbasic | arch/zx48k/backend/__f16.py | _f16_oper | def _f16_oper(op1, op2=None, useBC=False, reversed=False):
""" Returns pop sequence for 32 bits operands
1st operand in HLDE, 2nd operand remains in the stack
Now it does support operands inversion calling __SWAP32.
However, if 1st operand is integer (immediate) or indirect, the stack
will be rearranged, so it contains a 32 bit pushed parameter value for the
subroutine to be called.
If preserveHL is True, then BC will be used instead of HL for lower part
for the 1st operand.
"""
output = []
if op1 is not None:
op1 = str(op1)
if op2 is not None:
op2 = str(op2)
op = op2 if op2 is not None else op1
float1 = False # whether op1 (2nd operand) is float
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
hl = 'hl' if not useBC and not indirect else 'bc'
if is_float(op):
float1 = True
op = float(op)
if indirect:
op = int(op) & 0xFFFF
if immediate:
output.append('ld hl, %i' % op)
else:
output.append('ld hl, (%i)' % op)
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
if preserveHL: # noqa TODO: it will fail
output.append('ld b, h')
output.append('ld c, l')
else:
DE, HL = f16(op)
output.append('ld de, %i' % DE)
output.append('ld %s, %i' % (hl, HL))
else:
if op[0] == '_':
if immediate:
output.append('ld %s, %s' % (hl, op))
else:
output.append('ld %s, (%s)' % (hl, op))
else:
output.append('pop %s' % hl)
if indirect:
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
if preserveHL: # noqa TODO: it will fail
output.append('ld b, h')
output.append('ld c, l')
else:
if op[0] == '_':
output.append('ld de, (%s + 2)' % op)
else:
output.append('pop de')
if op2 is not None:
op = op1
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_float(op):
op = float(op)
if indirect:
op = int(op)
output.append('exx')
if immediate:
output.append('ld hl, %i' % (op & 0xFFFF))
else:
output.append('ld hl, (%i)' % (op & 0xFFFF))
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
output.append('exx')
REQUIRES.add('iload32.asm')
else:
DE, HL = f16(op)
output.append('ld bc, %i' % DE)
output.append('push bc')
output.append('ld bc, %i' % HL)
output.append('push bc')
else:
if indirect:
output.append('exx') # uses alternate set to put it on the stack
if op[0] == '_':
if immediate:
output.append('ld hl, %s' % op)
else:
output.append('ld hl, (%s)' % op)
else:
output.append('pop hl') # Pointers are only 16 bits ***
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
output.append('exx')
REQUIRES.add('iload32.asm')
elif op[0] == '_': # an address
if float1 or op1[0] == '_': # If previous op was constant, we can use hl in advance
tmp = output
output = []
output.append('ld hl, (%s + 2)' % op)
output.append('push hl')
output.append('ld hl, (%s)' % op)
output.append('push hl')
output.extend(tmp)
else:
output.append('ld bc, (%s + 2)' % op)
output.append('push bc')
output.append('ld bc, (%s)' % op)
output.append('push bc')
else:
pass # 2nd operand remains in the stack
if op2 is not None and reversed:
output.append('call __SWAP32')
REQUIRES.add('swap32.asm')
return output | python | def _f16_oper(op1, op2=None, useBC=False, reversed=False):
""" Returns pop sequence for 32 bits operands
1st operand in HLDE, 2nd operand remains in the stack
Now it does support operands inversion calling __SWAP32.
However, if 1st operand is integer (immediate) or indirect, the stack
will be rearranged, so it contains a 32 bit pushed parameter value for the
subroutine to be called.
If preserveHL is True, then BC will be used instead of HL for lower part
for the 1st operand.
"""
output = []
if op1 is not None:
op1 = str(op1)
if op2 is not None:
op2 = str(op2)
op = op2 if op2 is not None else op1
float1 = False # whether op1 (2nd operand) is float
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
hl = 'hl' if not useBC and not indirect else 'bc'
if is_float(op):
float1 = True
op = float(op)
if indirect:
op = int(op) & 0xFFFF
if immediate:
output.append('ld hl, %i' % op)
else:
output.append('ld hl, (%i)' % op)
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
if preserveHL: # noqa TODO: it will fail
output.append('ld b, h')
output.append('ld c, l')
else:
DE, HL = f16(op)
output.append('ld de, %i' % DE)
output.append('ld %s, %i' % (hl, HL))
else:
if op[0] == '_':
if immediate:
output.append('ld %s, %s' % (hl, op))
else:
output.append('ld %s, (%s)' % (hl, op))
else:
output.append('pop %s' % hl)
if indirect:
output.append('call __ILOAD32')
REQUIRES.add('iload32.asm')
if preserveHL: # noqa TODO: it will fail
output.append('ld b, h')
output.append('ld c, l')
else:
if op[0] == '_':
output.append('ld de, (%s + 2)' % op)
else:
output.append('pop de')
if op2 is not None:
op = op1
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_float(op):
op = float(op)
if indirect:
op = int(op)
output.append('exx')
if immediate:
output.append('ld hl, %i' % (op & 0xFFFF))
else:
output.append('ld hl, (%i)' % (op & 0xFFFF))
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
output.append('exx')
REQUIRES.add('iload32.asm')
else:
DE, HL = f16(op)
output.append('ld bc, %i' % DE)
output.append('push bc')
output.append('ld bc, %i' % HL)
output.append('push bc')
else:
if indirect:
output.append('exx') # uses alternate set to put it on the stack
if op[0] == '_':
if immediate:
output.append('ld hl, %s' % op)
else:
output.append('ld hl, (%s)' % op)
else:
output.append('pop hl') # Pointers are only 16 bits ***
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
output.append('exx')
REQUIRES.add('iload32.asm')
elif op[0] == '_': # an address
if float1 or op1[0] == '_': # If previous op was constant, we can use hl in advance
tmp = output
output = []
output.append('ld hl, (%s + 2)' % op)
output.append('push hl')
output.append('ld hl, (%s)' % op)
output.append('push hl')
output.extend(tmp)
else:
output.append('ld bc, (%s + 2)' % op)
output.append('push bc')
output.append('ld bc, (%s)' % op)
output.append('push bc')
else:
pass # 2nd operand remains in the stack
if op2 is not None and reversed:
output.append('call __SWAP32')
REQUIRES.add('swap32.asm')
return output | Returns pop sequence for 32 bits operands
1st operand in HLDE, 2nd operand remains in the stack
Now it does support operands inversion calling __SWAP32.
However, if 1st operand is integer (immediate) or indirect, the stack
will be rearranged, so it contains a 32 bit pushed parameter value for the
subroutine to be called.
If preserveHL is True, then BC will be used instead of HL for lower part
for the 1st operand. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__f16.py#L48-L196 |
boriel/zxbasic | arch/zx48k/backend/__f16.py | _f16_to_32bit | def _f16_to_32bit(ins):
""" If any of the operands within the ins(truction) are numeric,
convert them to its 32bit representation, otherwise leave them
as they are.
"""
ins.quad = [x for x in ins.quad]
for i in range(2, len(ins.quad)):
if is_float(ins.quad[i]):
de, hl = f16(ins.quad[i])
ins.quad[i] = str((de << 16) | hl)
ins.quad = tuple(ins.quad)
return ins | python | def _f16_to_32bit(ins):
""" If any of the operands within the ins(truction) are numeric,
convert them to its 32bit representation, otherwise leave them
as they are.
"""
ins.quad = [x for x in ins.quad]
for i in range(2, len(ins.quad)):
if is_float(ins.quad[i]):
de, hl = f16(ins.quad[i])
ins.quad[i] = str((de << 16) | hl)
ins.quad = tuple(ins.quad)
return ins | If any of the operands within the ins(truction) are numeric,
convert them to its 32bit representation, otherwise leave them
as they are. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__f16.py#L199-L211 |
boriel/zxbasic | arch/zx48k/backend/__f16.py | _mulf16 | def _mulf16(ins):
""" Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
"""
op1, op2 = tuple(ins.quad[2:])
if _f_ops(op1, op2) is not None:
op1, op2 = _f_ops(op1, op2)
if op2 == 1: # A * 1 => A
output = _f16_oper(op1)
output.append('push de')
output.append('push hl')
return output
if op2 == -1:
return _neg32(ins)
output = _f16_oper(op1)
if op2 == 0:
output.append('ld hl, 0')
output.append('ld e, h')
output.append('ld d, l')
output.append('push de')
output.append('push hl')
return output
output = _f16_oper(op1, str(op2))
output.append('call __MULF16')
output.append('push de')
output.append('push hl')
REQUIRES.add('mulf16.asm')
return output | python | def _mulf16(ins):
""" Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
"""
op1, op2 = tuple(ins.quad[2:])
if _f_ops(op1, op2) is not None:
op1, op2 = _f_ops(op1, op2)
if op2 == 1: # A * 1 => A
output = _f16_oper(op1)
output.append('push de')
output.append('push hl')
return output
if op2 == -1:
return _neg32(ins)
output = _f16_oper(op1)
if op2 == 0:
output.append('ld hl, 0')
output.append('ld e, h')
output.append('ld d, l')
output.append('push de')
output.append('push hl')
return output
output = _f16_oper(op1, str(op2))
output.append('call __MULF16')
output.append('push de')
output.append('push hl')
REQUIRES.add('mulf16.asm')
return output | Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__f16.py#L235-L266 |
boriel/zxbasic | arch/zx48k/backend/__f16.py | _divf16 | def _divf16(ins):
""" Divides 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1, do nothing
* If 2nd operand is -1, do NEG32
"""
op1, op2 = tuple(ins.quad[2:])
if is_float(op2):
if float(op2) == 1:
output = _f16_oper(op1)
output.append('push de')
output.append('push hl')
return output
if float(op2) == -1:
return _negf(ins)
rev = not is_float(op1) and op1[0] != 't' and op2[0] == 't'
output = _f16_oper(op1, op2, reversed=rev)
output.append('call __DIVF16')
output.append('push de')
output.append('push hl')
REQUIRES.add('divf16.asm')
return output | python | def _divf16(ins):
""" Divides 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1, do nothing
* If 2nd operand is -1, do NEG32
"""
op1, op2 = tuple(ins.quad[2:])
if is_float(op2):
if float(op2) == 1:
output = _f16_oper(op1)
output.append('push de')
output.append('push hl')
return output
if float(op2) == -1:
return _negf(ins)
rev = not is_float(op1) and op1[0] != 't' and op2[0] == 't'
output = _f16_oper(op1, op2, reversed=rev)
output.append('call __DIVF16')
output.append('push de')
output.append('push hl')
REQUIRES.add('divf16.asm')
return output | Divides 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1, do nothing
* If 2nd operand is -1, do NEG32 | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__f16.py#L269-L296 |
boriel/zxbasic | arch/zx48k/backend/errors.py | throw_invalid_quad_params | def throw_invalid_quad_params(quad, QUADS, nparams):
""" Exception raised when an invalid number of params in the
quad code has been emmitted.
"""
raise InvalidICError(str(quad),
"Invalid quad code params for '%s' (expected %i, but got %i)" %
(quad, QUADS[quad][0], nparams)
) | python | def throw_invalid_quad_params(quad, QUADS, nparams):
""" Exception raised when an invalid number of params in the
quad code has been emmitted.
"""
raise InvalidICError(str(quad),
"Invalid quad code params for '%s' (expected %i, but got %i)" %
(quad, QUADS[quad][0], nparams)
) | Exception raised when an invalid number of params in the
quad code has been emmitted. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/errors.py#L72-L79 |
boriel/zxbasic | api/fp.py | fp | def fp(x):
""" Returns a floating point number as EXP+128, Mantissa
"""
def bin32(f):
""" Returns ASCII representation for a 32 bit integer value
"""
result = ''
a = int(f) & 0xFFFFFFFF # ensures int 32
for i in range(32):
result = str(a % 2) + result
a = a >> 1
return result
def bindec32(f):
""" Returns binary representation of a mantissa x (x is float)
"""
result = '0'
a = f
if f >= 1:
result = bin32(f)
result += '.'
c = int(a)
for i in range(32):
a -= c
a *= 2
c = int(a)
result += str(c)
return result
e = 0 # exponent
s = 1 if x < 0 else 0 # sign
m = abs(x) # mantissa
while m >= 1:
m /= 2.0
e += 1
while 0 < m < 0.5:
m *= 2.0
e -= 1
M = bindec32(m)[3:]
M = str(s) + M
E = bin32(e + 128)[-8:] if x != 0 else bin32(0)[-8:]
return M, E | python | def fp(x):
""" Returns a floating point number as EXP+128, Mantissa
"""
def bin32(f):
""" Returns ASCII representation for a 32 bit integer value
"""
result = ''
a = int(f) & 0xFFFFFFFF # ensures int 32
for i in range(32):
result = str(a % 2) + result
a = a >> 1
return result
def bindec32(f):
""" Returns binary representation of a mantissa x (x is float)
"""
result = '0'
a = f
if f >= 1:
result = bin32(f)
result += '.'
c = int(a)
for i in range(32):
a -= c
a *= 2
c = int(a)
result += str(c)
return result
e = 0 # exponent
s = 1 if x < 0 else 0 # sign
m = abs(x) # mantissa
while m >= 1:
m /= 2.0
e += 1
while 0 < m < 0.5:
m *= 2.0
e -= 1
M = bindec32(m)[3:]
M = str(s) + M
E = bin32(e + 128)[-8:] if x != 0 else bin32(0)[-8:]
return M, E | Returns a floating point number as EXP+128, Mantissa | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/fp.py#L7-L59 |
boriel/zxbasic | api/fp.py | immediate_float | def immediate_float(x):
""" Returns C DE HL as values for loading
and immediate floating point.
"""
def bin2hex(y):
return "%02X" % int(y, 2)
M, E = fp(x)
C = '0' + bin2hex(E) + 'h'
ED = '0' + bin2hex(M[8:16]) + bin2hex(M[:8]) + 'h'
LH = '0' + bin2hex(M[24:]) + bin2hex(M[16:24]) + 'h'
return C, ED, LH | python | def immediate_float(x):
""" Returns C DE HL as values for loading
and immediate floating point.
"""
def bin2hex(y):
return "%02X" % int(y, 2)
M, E = fp(x)
C = '0' + bin2hex(E) + 'h'
ED = '0' + bin2hex(M[8:16]) + bin2hex(M[:8]) + 'h'
LH = '0' + bin2hex(M[24:]) + bin2hex(M[16:24]) + 'h'
return C, ED, LH | Returns C DE HL as values for loading
and immediate floating point. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/fp.py#L62-L75 |
boriel/zxbasic | ast_/tree.py | Tree.inorder | def inorder(self, funct, stopOn=None):
""" Iterates in order, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if stopOn is None:
for i in self.children:
i.inorder(funct)
else:
for i in self.children:
if i.inorder(funct) == stopOn:
return stopOn
return funct(self) | python | def inorder(self, funct, stopOn=None):
""" Iterates in order, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if stopOn is None:
for i in self.children:
i.inorder(funct)
else:
for i in self.children:
if i.inorder(funct) == stopOn:
return stopOn
return funct(self) | Iterates in order, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L101-L113 |
boriel/zxbasic | ast_/tree.py | Tree.preorder | def preorder(self, funct, stopOn=None):
""" Iterates in preorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if funct(self.symbol) == stopOn and stopOn is not None:
return stopOn
if stopOn is None:
for i in self.children:
i.preorder(funct)
else:
for i in self.children:
if i.preorder(funct) == stopOn:
return stopOn | python | def preorder(self, funct, stopOn=None):
""" Iterates in preorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if funct(self.symbol) == stopOn and stopOn is not None:
return stopOn
if stopOn is None:
for i in self.children:
i.preorder(funct)
else:
for i in self.children:
if i.preorder(funct) == stopOn:
return stopOn | Iterates in preorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L115-L128 |
boriel/zxbasic | ast_/tree.py | Tree.postorder | def postorder(self, funct, stopOn=None):
""" Iterates in postorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if stopOn is None:
for i in range(len(self.children) - 1, -1, -1):
self.children[i].postorder(funct)
else:
for i in range(len(self.children) - 1, -1, -1):
if self.children[i].postorder(funct) == stopOn:
return stopOn
return funct(self.symbol) | python | def postorder(self, funct, stopOn=None):
""" Iterates in postorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false.
"""
if stopOn is None:
for i in range(len(self.children) - 1, -1, -1):
self.children[i].postorder(funct)
else:
for i in range(len(self.children) - 1, -1, -1):
if self.children[i].postorder(funct) == stopOn:
return stopOn
return funct(self.symbol) | Iterates in postorder, calling the function with the current node.
If stopOn is set to True or False, it will stop on true or false. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L130-L141 |
boriel/zxbasic | ast_/tree.py | Tree.makenode | def makenode(clss, symbol, *nexts):
""" Stores the symbol in an AST instance,
and left and right to the given ones
"""
result = clss(symbol)
for i in nexts:
if i is None:
continue
if not isinstance(i, clss):
raise NotAnAstError(i)
result.appendChild(i)
return result | python | def makenode(clss, symbol, *nexts):
""" Stores the symbol in an AST instance,
and left and right to the given ones
"""
result = clss(symbol)
for i in nexts:
if i is None:
continue
if not isinstance(i, clss):
raise NotAnAstError(i)
result.appendChild(i)
return result | Stores the symbol in an AST instance,
and left and right to the given ones | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L154-L166 |
boriel/zxbasic | zxbpp.py | init | def init():
""" Initializes the preprocessor
"""
global OUTPUT
global INCLUDED
global CURRENT_DIR
global ENABLED
global INCLUDEPATH
global IFDEFS
global ID_TABLE
global CURRENT_FILE
global_.FILENAME = '(stdin)'
OUTPUT = ''
INCLUDED = {}
CURRENT_DIR = ''
pwd = get_include_path()
INCLUDEPATH = [os.path.join(pwd, 'library'), os.path.join(pwd, 'library-asm')]
ENABLED = True
IFDEFS = []
global_.has_errors = 0
global_.error_msg_cache.clear()
parser.defaulted_states = {}
ID_TABLE = DefinesTable()
del CURRENT_FILE[:] | python | def init():
""" Initializes the preprocessor
"""
global OUTPUT
global INCLUDED
global CURRENT_DIR
global ENABLED
global INCLUDEPATH
global IFDEFS
global ID_TABLE
global CURRENT_FILE
global_.FILENAME = '(stdin)'
OUTPUT = ''
INCLUDED = {}
CURRENT_DIR = ''
pwd = get_include_path()
INCLUDEPATH = [os.path.join(pwd, 'library'), os.path.join(pwd, 'library-asm')]
ENABLED = True
IFDEFS = []
global_.has_errors = 0
global_.error_msg_cache.clear()
parser.defaulted_states = {}
ID_TABLE = DefinesTable()
del CURRENT_FILE[:] | Initializes the preprocessor | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L62-L86 |
boriel/zxbasic | zxbpp.py | get_include_path | def get_include_path():
""" Default include path using a tricky sys
calls.
"""
f1 = os.path.basename(sys.argv[0]).lower() # script filename
f2 = os.path.basename(sys.executable).lower() # Executable filename
# If executable filename and script name are the same, we are
if f1 == f2 or f2 == f1 + '.exe': # under a "compiled" python binary
result = os.path.dirname(os.path.realpath(sys.executable))
else:
result = os.path.dirname(os.path.realpath(__file__))
return result | python | def get_include_path():
""" Default include path using a tricky sys
calls.
"""
f1 = os.path.basename(sys.argv[0]).lower() # script filename
f2 = os.path.basename(sys.executable).lower() # Executable filename
# If executable filename and script name are the same, we are
if f1 == f2 or f2 == f1 + '.exe': # under a "compiled" python binary
result = os.path.dirname(os.path.realpath(sys.executable))
else:
result = os.path.dirname(os.path.realpath(__file__))
return result | Default include path using a tricky sys
calls. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L89-L102 |
boriel/zxbasic | zxbpp.py | search_filename | def search_filename(fname, lineno, local_first):
""" Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed.
"""
fname = api.utils.sanitize_filename(fname)
i_path = [CURRENT_DIR] + INCLUDEPATH if local_first else list(INCLUDEPATH)
i_path.extend(OPTIONS.include_path.value.split(':') if OPTIONS.include_path.value else [])
if os.path.isabs(fname):
if os.path.isfile(fname):
return fname
else:
for dir_ in i_path:
path = api.utils.sanitize_filename(os.path.join(dir_, fname))
if os.path.exists(path):
return path
error(lineno, "file '%s' not found" % fname)
return '' | python | def search_filename(fname, lineno, local_first):
""" Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed.
"""
fname = api.utils.sanitize_filename(fname)
i_path = [CURRENT_DIR] + INCLUDEPATH if local_first else list(INCLUDEPATH)
i_path.extend(OPTIONS.include_path.value.split(':') if OPTIONS.include_path.value else [])
if os.path.isabs(fname):
if os.path.isfile(fname):
return fname
else:
for dir_ in i_path:
path = api.utils.sanitize_filename(os.path.join(dir_, fname))
if os.path.exists(path):
return path
error(lineno, "file '%s' not found" % fname)
return '' | Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed. | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L118-L136 |
boriel/zxbasic | zxbpp.py | include_file | def include_file(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename".
"""
global CURRENT_DIR
filename = search_filename(filename, lineno, local_first)
if filename not in INCLUDED.keys():
INCLUDED[filename] = []
if len(CURRENT_FILE) > 0: # Added from which file, line
INCLUDED[filename].append((CURRENT_FILE[-1], lineno))
CURRENT_FILE.append(filename)
CURRENT_DIR = os.path.dirname(filename)
return LEXER.include(filename) | python | def include_file(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename".
"""
global CURRENT_DIR
filename = search_filename(filename, lineno, local_first)
if filename not in INCLUDED.keys():
INCLUDED[filename] = []
if len(CURRENT_FILE) > 0: # Added from which file, line
INCLUDED[filename].append((CURRENT_FILE[-1], lineno))
CURRENT_FILE.append(filename)
CURRENT_DIR = os.path.dirname(filename)
return LEXER.include(filename) | Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename". | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L139-L158 |
boriel/zxbasic | zxbpp.py | include_once | def include_once(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
The file is ignored if it was previuosly included (a warning will
be emitted though).
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename".
"""
filename = search_filename(filename, lineno, local_first)
if filename not in INCLUDED.keys(): # If not already included
return include_file(filename, lineno, local_first) # include it and return
# Now checks if the file has been included more than once
if len(INCLUDED[filename]) > 1:
warning(lineno, "file '%s' already included more than once, in file "
"'%s' at line %i" %
(filename, INCLUDED[filename][0][0], INCLUDED[filename][0][1]))
# Empty file (already included)
LEXER.next_token = '_ENDFILE_'
return '' | python | def include_once(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
The file is ignored if it was previuosly included (a warning will
be emitted though).
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename".
"""
filename = search_filename(filename, lineno, local_first)
if filename not in INCLUDED.keys(): # If not already included
return include_file(filename, lineno, local_first) # include it and return
# Now checks if the file has been included more than once
if len(INCLUDED[filename]) > 1:
warning(lineno, "file '%s' already included more than once, in file "
"'%s' at line %i" %
(filename, INCLUDED[filename][0][0], INCLUDED[filename][0][1]))
# Empty file (already included)
LEXER.next_token = '_ENDFILE_'
return '' | Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
The file is ignored if it was previuosly included (a warning will
be emitted though).
If local_first is True, then it will first search the file in the
local path before looking for it in the include path chain.
This is used when doing a #include "filename". | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L161-L185 |
boriel/zxbasic | zxbpp.py | p_program_tokenstring | def p_program_tokenstring(p):
""" program : defs NEWLINE
"""
try:
tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[1]]
except PreprocError as v:
error(v.lineno, v.message)
tmp.append(p[2])
p[0] = tmp | python | def p_program_tokenstring(p):
""" program : defs NEWLINE
"""
try:
tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[1]]
except PreprocError as v:
error(v.lineno, v.message)
tmp.append(p[2])
p[0] = tmp | program : defs NEWLINE | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L211-L220 |
boriel/zxbasic | zxbpp.py | p_include_file | def p_include_file(p):
""" include_file : include NEWLINE program _ENDFILE_
"""
global CURRENT_DIR
p[0] = [p[1] + p[2]] + p[3] + [p[4]]
CURRENT_FILE.pop() # Remove top of the stack
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1]) | python | def p_include_file(p):
""" include_file : include NEWLINE program _ENDFILE_
"""
global CURRENT_DIR
p[0] = [p[1] + p[2]] + p[3] + [p[4]]
CURRENT_FILE.pop() # Remove top of the stack
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1]) | include_file : include NEWLINE program _ENDFILE_ | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L274-L280 |
boriel/zxbasic | zxbpp.py | p_include_once_ok | def p_include_once_ok(p):
""" include_file : include_once NEWLINE program _ENDFILE_
"""
global CURRENT_DIR
p[0] = [p[1] + p[2]] + p[3] + [p[4]]
CURRENT_FILE.pop() # Remove top of the stack
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1]) | python | def p_include_once_ok(p):
""" include_file : include_once NEWLINE program _ENDFILE_
"""
global CURRENT_DIR
p[0] = [p[1] + p[2]] + p[3] + [p[4]]
CURRENT_FILE.pop() # Remove top of the stack
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1]) | include_file : include_once NEWLINE program _ENDFILE_ | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L295-L301 |
boriel/zxbasic | zxbpp.py | p_include | def p_include(p):
""" include : INCLUDE STRING
"""
if ENABLED:
p[0] = include_file(p[2], p.lineno(2), local_first=True)
else:
p[0] = []
p.lexer.next_token = '_ENDFILE_' | python | def p_include(p):
""" include : INCLUDE STRING
"""
if ENABLED:
p[0] = include_file(p[2], p.lineno(2), local_first=True)
else:
p[0] = []
p.lexer.next_token = '_ENDFILE_' | include : INCLUDE STRING | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L304-L311 |
boriel/zxbasic | zxbpp.py | p_include_fname | def p_include_fname(p):
""" include : INCLUDE FILENAME
"""
if ENABLED:
p[0] = include_file(p[2], p.lineno(2), local_first=False)
else:
p[0] = []
p.lexer.next_token = '_ENDFILE_' | python | def p_include_fname(p):
""" include : INCLUDE FILENAME
"""
if ENABLED:
p[0] = include_file(p[2], p.lineno(2), local_first=False)
else:
p[0] = []
p.lexer.next_token = '_ENDFILE_' | include : INCLUDE FILENAME | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L314-L321 |
boriel/zxbasic | zxbpp.py | p_include_once | def p_include_once(p):
""" include_once : INCLUDE ONCE STRING
"""
if ENABLED:
p[0] = include_once(p[3], p.lineno(3), local_first=True)
else:
p[0] = []
if not p[0]:
p.lexer.next_token = '_ENDFILE_' | python | def p_include_once(p):
""" include_once : INCLUDE ONCE STRING
"""
if ENABLED:
p[0] = include_once(p[3], p.lineno(3), local_first=True)
else:
p[0] = []
if not p[0]:
p.lexer.next_token = '_ENDFILE_' | include_once : INCLUDE ONCE STRING | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L324-L333 |
boriel/zxbasic | zxbpp.py | p_include_once_fname | def p_include_once_fname(p):
""" include_once : INCLUDE ONCE FILENAME
"""
p[0] = []
if ENABLED:
p[0] = include_once(p[3], p.lineno(3), local_first=False)
else:
p[0] = []
if not p[0]:
p.lexer.next_token = '_ENDFILE_' | python | def p_include_once_fname(p):
""" include_once : INCLUDE ONCE FILENAME
"""
p[0] = []
if ENABLED:
p[0] = include_once(p[3], p.lineno(3), local_first=False)
else:
p[0] = []
if not p[0]:
p.lexer.next_token = '_ENDFILE_' | include_once : INCLUDE ONCE FILENAME | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L336-L347 |
boriel/zxbasic | zxbpp.py | p_define | def p_define(p):
""" define : DEFINE ID params defs
"""
if ENABLED:
if p[4]:
if SPACES.match(p[4][0]):
p[4][0] = p[4][0][1:]
else:
warning(p.lineno(1), "missing whitespace after the macro name")
ID_TABLE.define(p[2], args=p[3], value=p[4], lineno=p.lineno(2),
fname=CURRENT_FILE[-1])
p[0] = [] | python | def p_define(p):
""" define : DEFINE ID params defs
"""
if ENABLED:
if p[4]:
if SPACES.match(p[4][0]):
p[4][0] = p[4][0][1:]
else:
warning(p.lineno(1), "missing whitespace after the macro name")
ID_TABLE.define(p[2], args=p[3], value=p[4], lineno=p.lineno(2),
fname=CURRENT_FILE[-1])
p[0] = [] | define : DEFINE ID params defs | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L406-L418 |
boriel/zxbasic | zxbpp.py | p_define_params_empty | def p_define_params_empty(p):
""" params : LP RP
"""
# Defines the 'epsilon' parameter
p[0] = [ID('', value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | python | def p_define_params_empty(p):
""" params : LP RP
"""
# Defines the 'epsilon' parameter
p[0] = [ID('', value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | params : LP RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L427-L432 |
boriel/zxbasic | zxbpp.py | p_define_params_paramlist | def p_define_params_paramlist(p):
""" params : LP paramlist RP
"""
for i in p[2]:
if not isinstance(i, ID):
error(p.lineno(3),
'"%s" might not appear in a macro parameter list' % str(i))
p[0] = None
return
names = [x.name for x in p[2]]
for i in range(len(names)):
if names[i] in names[i + 1:]:
error(p.lineno(3),
'Duplicated name parameter "%s"' % (names[i]))
p[0] = None
return
p[0] = p[2] | python | def p_define_params_paramlist(p):
""" params : LP paramlist RP
"""
for i in p[2]:
if not isinstance(i, ID):
error(p.lineno(3),
'"%s" might not appear in a macro parameter list' % str(i))
p[0] = None
return
names = [x.name for x in p[2]]
for i in range(len(names)):
if names[i] in names[i + 1:]:
error(p.lineno(3),
'Duplicated name parameter "%s"' % (names[i]))
p[0] = None
return
p[0] = p[2] | params : LP paramlist RP | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L435-L453 |
boriel/zxbasic | zxbpp.py | p_paramlist_single | def p_paramlist_single(p):
""" paramlist : ID
"""
p[0] = [ID(p[1], value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | python | def p_paramlist_single(p):
""" paramlist : ID
"""
p[0] = [ID(p[1], value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | paramlist : ID | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L456-L460 |
boriel/zxbasic | zxbpp.py | p_paramlist_paramlist | def p_paramlist_paramlist(p):
""" paramlist : paramlist COMMA ID
"""
p[0] = p[1] + [ID(p[3], value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | python | def p_paramlist_paramlist(p):
""" paramlist : paramlist COMMA ID
"""
p[0] = p[1] + [ID(p[3], value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | paramlist : paramlist COMMA ID | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L463-L467 |
boriel/zxbasic | zxbpp.py | p_ifdef | def p_ifdef(p):
""" ifdef : if_header NEWLINE program ENDIF
"""
global ENABLED
if ENABLED:
p[0] = [p[2]] + p[3]
p[0] += ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])]
else:
p[0] = ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])]
ENABLED = IFDEFS[-1][0]
IFDEFS.pop() | python | def p_ifdef(p):
""" ifdef : if_header NEWLINE program ENDIF
"""
global ENABLED
if ENABLED:
p[0] = [p[2]] + p[3]
p[0] += ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])]
else:
p[0] = ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])]
ENABLED = IFDEFS[-1][0]
IFDEFS.pop() | ifdef : if_header NEWLINE program ENDIF | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L491-L503 |
boriel/zxbasic | zxbpp.py | p_ifdef_else | def p_ifdef_else(p):
""" ifdef : ifdefelsea ifdefelseb ENDIF
"""
global ENABLED
p[0] = p[1] + p[2]
p[0] += ['#line %i "%s"' % (p.lineno(3) + 1, CURRENT_FILE[-1])]
ENABLED = IFDEFS[-1][0]
IFDEFS.pop() | python | def p_ifdef_else(p):
""" ifdef : ifdefelsea ifdefelseb ENDIF
"""
global ENABLED
p[0] = p[1] + p[2]
p[0] += ['#line %i "%s"' % (p.lineno(3) + 1, CURRENT_FILE[-1])]
ENABLED = IFDEFS[-1][0]
IFDEFS.pop() | ifdef : ifdefelsea ifdefelseb ENDIF | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L506-L514 |
boriel/zxbasic | zxbpp.py | p_ifdef_else_a | def p_ifdef_else_a(p):
""" ifdefelsea : if_header NEWLINE program
"""
global ENABLED
if ENABLED:
p[0] = [p[2]] + p[3]
else:
p[0] = []
ENABLED = not ENABLED | python | def p_ifdef_else_a(p):
""" ifdefelsea : if_header NEWLINE program
"""
global ENABLED
if ENABLED:
p[0] = [p[2]] + p[3]
else:
p[0] = []
ENABLED = not ENABLED | ifdefelsea : if_header NEWLINE program | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L517-L527 |
boriel/zxbasic | zxbpp.py | p_ifdef_else_b | def p_ifdef_else_b(p):
""" ifdefelseb : ELSE NEWLINE program
"""
global ENABLED
if ENABLED:
p[0] = ['#line %i "%s"%s' % (p.lineno(1) + 1, CURRENT_FILE[-1], p[2])]
p[0] += p[3]
else:
p[0] = [] | python | def p_ifdef_else_b(p):
""" ifdefelseb : ELSE NEWLINE program
"""
global ENABLED
if ENABLED:
p[0] = ['#line %i "%s"%s' % (p.lineno(1) + 1, CURRENT_FILE[-1], p[2])]
p[0] += p[3]
else:
p[0] = [] | ifdefelseb : ELSE NEWLINE program | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L530-L539 |
boriel/zxbasic | zxbpp.py | p_if_header | def p_if_header(p):
""" if_header : IFDEF ID
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(2)))
ENABLED = ID_TABLE.defined(p[2]) | python | def p_if_header(p):
""" if_header : IFDEF ID
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(2)))
ENABLED = ID_TABLE.defined(p[2]) | if_header : IFDEF ID | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L542-L548 |
boriel/zxbasic | zxbpp.py | p_ifn_header | def p_ifn_header(p):
""" if_header : IFNDEF ID
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(2)))
ENABLED = not ID_TABLE.defined(p[2]) | python | def p_ifn_header(p):
""" if_header : IFNDEF ID
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(2)))
ENABLED = not ID_TABLE.defined(p[2]) | if_header : IFNDEF ID | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L551-L557 |
boriel/zxbasic | zxbpp.py | p_if_expr_header | def p_if_expr_header(p):
""" if_header : IF expr
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(1)))
ENABLED = bool(int(p[2])) if p[2].isdigit() else ID_TABLE.defined(p[2]) | python | def p_if_expr_header(p):
""" if_header : IF expr
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(1)))
ENABLED = bool(int(p[2])) if p[2].isdigit() else ID_TABLE.defined(p[2]) | if_header : IF expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L560-L566 |
boriel/zxbasic | zxbpp.py | p_exprlt | def p_exprlt(p):
""" expr : expr LT expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a < b else '0' | python | def p_exprlt(p):
""" expr : expr LT expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a < b else '0' | expr : expr LT expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L587-L593 |
boriel/zxbasic | zxbpp.py | p_exprle | def p_exprle(p):
""" expr : expr LE expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a <= b else '0' | python | def p_exprle(p):
""" expr : expr LE expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a <= b else '0' | expr : expr LE expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L596-L602 |
boriel/zxbasic | zxbpp.py | p_exprgt | def p_exprgt(p):
""" expr : expr GT expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a > b else '0' | python | def p_exprgt(p):
""" expr : expr GT expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a > b else '0' | expr : expr GT expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L605-L611 |
boriel/zxbasic | zxbpp.py | p_exprge | def p_exprge(p):
""" expr : expr GE expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a >= b else '0' | python | def p_exprge(p):
""" expr : expr GE expr
"""
a = int(p[1]) if p[1].isdigit() else 0
b = int(p[3]) if p[3].isdigit() else 0
p[0] = '1' if a >= b else '0' | expr : expr GE expr | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L614-L620 |
boriel/zxbasic | zxbpp.py | filter_ | def filter_(input_, filename='<internal>', state='INITIAL'):
""" Filter the input string thought the preprocessor.
result is appended to OUTPUT global str
"""
global CURRENT_DIR
prev_dir = CURRENT_DIR
CURRENT_FILE.append(filename)
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1])
LEXER.input(input_, filename)
LEXER.lex.begin(state)
parser.parse(lexer=LEXER, debug=OPTIONS.Debug.value > 2)
CURRENT_FILE.pop()
CURRENT_DIR = prev_dir | python | def filter_(input_, filename='<internal>', state='INITIAL'):
""" Filter the input string thought the preprocessor.
result is appended to OUTPUT global str
"""
global CURRENT_DIR
prev_dir = CURRENT_DIR
CURRENT_FILE.append(filename)
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1])
LEXER.input(input_, filename)
LEXER.lex.begin(state)
parser.parse(lexer=LEXER, debug=OPTIONS.Debug.value > 2)
CURRENT_FILE.pop()
CURRENT_DIR = prev_dir | Filter the input string thought the preprocessor.
result is appended to OUTPUT global str | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L736-L749 |
MAVENSDC/PyTplot | pytplot/del_data.py | del_data | def del_data(name=None):
"""
This function will delete tplot variables that are already stored in memory.
Parameters:
name : str
Name of the tplot variable to be deleted. If no name is provided, then
all tplot variables will be deleted.
Returns:
None
Examples:
>>> # Delete Variable 1
>>> import pytplot
>>> pytplot.del_data("Variable1")
"""
if name is None:
tplot_names = list(data_quants.keys())
for i in tplot_names:
del data_quants[i]
return
if not isinstance(name, list):
name = [name]
entries = []
###
for i in name:
if ('?' in i) or ('*' in i):
for j in data_quants.keys():
var_verif = fnmatch.fnmatch(data_quants[j].name, i)
if var_verif == 1:
entries.append(data_quants[j].name)
else:
continue
for key in entries:
if key in data_quants:
del data_quants[key]
###
elif i not in data_quants.keys():
print(str(i) + " is currently not in pytplot.")
return
else:
temp_data_quants = data_quants[i]
str_name = temp_data_quants.name
del data_quants[str_name]
return | python | def del_data(name=None):
"""
This function will delete tplot variables that are already stored in memory.
Parameters:
name : str
Name of the tplot variable to be deleted. If no name is provided, then
all tplot variables will be deleted.
Returns:
None
Examples:
>>> # Delete Variable 1
>>> import pytplot
>>> pytplot.del_data("Variable1")
"""
if name is None:
tplot_names = list(data_quants.keys())
for i in tplot_names:
del data_quants[i]
return
if not isinstance(name, list):
name = [name]
entries = []
###
for i in name:
if ('?' in i) or ('*' in i):
for j in data_quants.keys():
var_verif = fnmatch.fnmatch(data_quants[j].name, i)
if var_verif == 1:
entries.append(data_quants[j].name)
else:
continue
for key in entries:
if key in data_quants:
del data_quants[key]
###
elif i not in data_quants.keys():
print(str(i) + " is currently not in pytplot.")
return
else:
temp_data_quants = data_quants[i]
str_name = temp_data_quants.name
del data_quants[str_name]
return | This function will delete tplot variables that are already stored in memory.
Parameters:
name : str
Name of the tplot variable to be deleted. If no name is provided, then
all tplot variables will be deleted.
Returns:
None
Examples:
>>> # Delete Variable 1
>>> import pytplot
>>> pytplot.del_data("Variable1") | https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/del_data.py#L9-L60 |
MAVENSDC/PyTplot | pytplot/xlim.py | xlim | def xlim(min, max):
"""
This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
max : flt
The time to end all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
Returns:
None
Examples:
>>> # Set the timespan to be 2017-07-17 00:00:00 plus 1 day
>>> import pytplot
>>> pytplot.xlim(1500249600, 1500249600 + 86400)
>>> # The same as above, but using different inputs
>>> pytplot.xlim("2017-07-17 00:00:00", "2017-07-18 00:00:00")
"""
if not isinstance(min, (int, float, complex)):
min = tplot_utilities.str_to_int(min)
if not isinstance(max, (int, float, complex)):
max = tplot_utilities.str_to_int(max)
if 'x_range' in tplot_opt_glob:
lim_info['xlast'] = tplot_opt_glob['x_range']
else:
lim_info['xfull'] = Range1d(min, max)
lim_info['xlast'] = Range1d(min, max)
tplot_opt_glob['x_range'] = [min, max]
return | python | def xlim(min, max):
"""
This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
max : flt
The time to end all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
Returns:
None
Examples:
>>> # Set the timespan to be 2017-07-17 00:00:00 plus 1 day
>>> import pytplot
>>> pytplot.xlim(1500249600, 1500249600 + 86400)
>>> # The same as above, but using different inputs
>>> pytplot.xlim("2017-07-17 00:00:00", "2017-07-18 00:00:00")
"""
if not isinstance(min, (int, float, complex)):
min = tplot_utilities.str_to_int(min)
if not isinstance(max, (int, float, complex)):
max = tplot_utilities.str_to_int(max)
if 'x_range' in tplot_opt_glob:
lim_info['xlast'] = tplot_opt_glob['x_range']
else:
lim_info['xfull'] = Range1d(min, max)
lim_info['xlast'] = Range1d(min, max)
tplot_opt_glob['x_range'] = [min, max]
return | This function will set the x axis range for all time series plots
Parameters:
min : flt
The time to start all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
max : flt
The time to end all time series plots. Can be given in seconds since epoch, or as a string
in the format "YYYY-MM-DD HH:MM:SS"
Returns:
None
Examples:
>>> # Set the timespan to be 2017-07-17 00:00:00 plus 1 day
>>> import pytplot
>>> pytplot.xlim(1500249600, 1500249600 + 86400)
>>> # The same as above, but using different inputs
>>> pytplot.xlim("2017-07-17 00:00:00", "2017-07-18 00:00:00") | https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/xlim.py#L10-L44 |
MAVENSDC/PyTplot | pytplot/zlim.py | zlim | def zlim(name, min, max):
"""
This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The name of the tplot variable that you wish to set z limits for.
min : flt
The start of the z axis.
max : flt
The end of the z axis.
Returns:
None
Examples:
>>> # Change the z range of Variable1
>>> import pytplot
>>> x_data = [1,2,3]
>>> y_data = [ [1,2,3] , [4,5,6], [7,8,9] ]
>>> v_data = [1,2,3]
>>> pytplot.store_data("Variable3", data={'x':x_data, 'y':y_data, 'v':v_data})
>>> pytplot.zlim('Variable1', 2, 3)
"""
if name not in data_quants.keys():
print("That name is currently not in pytplot.")
return
temp_data_quant = data_quants[name]
temp_data_quant.zaxis_opt['z_range'] = [min, max]
return | python | def zlim(name, min, max):
"""
This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The name of the tplot variable that you wish to set z limits for.
min : flt
The start of the z axis.
max : flt
The end of the z axis.
Returns:
None
Examples:
>>> # Change the z range of Variable1
>>> import pytplot
>>> x_data = [1,2,3]
>>> y_data = [ [1,2,3] , [4,5,6], [7,8,9] ]
>>> v_data = [1,2,3]
>>> pytplot.store_data("Variable3", data={'x':x_data, 'y':y_data, 'v':v_data})
>>> pytplot.zlim('Variable1', 2, 3)
"""
if name not in data_quants.keys():
print("That name is currently not in pytplot.")
return
temp_data_quant = data_quants[name]
temp_data_quant.zaxis_opt['z_range'] = [min, max]
return | This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The name of the tplot variable that you wish to set z limits for.
min : flt
The start of the z axis.
max : flt
The end of the z axis.
Returns:
None
Examples:
>>> # Change the z range of Variable1
>>> import pytplot
>>> x_data = [1,2,3]
>>> y_data = [ [1,2,3] , [4,5,6], [7,8,9] ]
>>> v_data = [1,2,3]
>>> pytplot.store_data("Variable3", data={'x':x_data, 'y':y_data, 'v':v_data})
>>> pytplot.zlim('Variable1', 2, 3) | https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/zlim.py#L8-L42 |
MAVENSDC/PyTplot | pytplot/ylim.py | ylim | def ylim(name, min, max):
"""
This function will set the y axis range displayed for a specific tplot variable.
Parameters:
name : str
The name of the tplot variable that you wish to set y limits for.
min : flt
The start of the y axis.
max : flt
The end of the y axis.
Returns:
None
Examples:
>>> # Change the y range of Variable1
>>> import pytplot
>>> x_data = [1,2,3,4,5]
>>> y_data = [1,2,3,4,5]
>>> pytplot.store_data("Variable1", data={'x':x_data, 'y':y_data})
>>> pytplot.ylim('Variable1', 2, 4)
"""
if name not in data_quants.keys():
print("That name is currently not in pytplot.")
return
temp_data_quant = data_quants[name]
temp_data_quant.yaxis_opt['y_range'] = [min, max]
return | python | def ylim(name, min, max):
"""
This function will set the y axis range displayed for a specific tplot variable.
Parameters:
name : str
The name of the tplot variable that you wish to set y limits for.
min : flt
The start of the y axis.
max : flt
The end of the y axis.
Returns:
None
Examples:
>>> # Change the y range of Variable1
>>> import pytplot
>>> x_data = [1,2,3,4,5]
>>> y_data = [1,2,3,4,5]
>>> pytplot.store_data("Variable1", data={'x':x_data, 'y':y_data})
>>> pytplot.ylim('Variable1', 2, 4)
"""
if name not in data_quants.keys():
print("That name is currently not in pytplot.")
return
temp_data_quant = data_quants[name]
temp_data_quant.yaxis_opt['y_range'] = [min, max]
return | This function will set the y axis range displayed for a specific tplot variable.
Parameters:
name : str
The name of the tplot variable that you wish to set y limits for.
min : flt
The start of the y axis.
max : flt
The end of the y axis.
Returns:
None
Examples:
>>> # Change the y range of Variable1
>>> import pytplot
>>> x_data = [1,2,3,4,5]
>>> y_data = [1,2,3,4,5]
>>> pytplot.store_data("Variable1", data={'x':x_data, 'y':y_data})
>>> pytplot.ylim('Variable1', 2, 4) | https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/ylim.py#L8-L39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.